I'm trying to get access to ng content with @ContentChild. To better understand @ContentChild I tried to implement a simple code example. I also did research such as here What's the difference between @ViewChild and @ContentChild?
还有更多的页面,但我已经坐在上面几个小时了,有以下问题.
如果我想在控制台中输出变量this.child
,则会显示undefined
.为什么会这样?我做错了什么?我需要做些什么不同的事情?
App-Root:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<应用程序-家长>
<应用程序- children ></应用程序- children >
</应用程序-家长>
`
})
export class AppComponent {}
应用程序-家长
import { AfterContentInit, Component, ContentChild} from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: '应用程序-家长',
template: `
<ng-content></ng-content>
`
})
export class ParentComponent implements AfterContentInit {
@ContentChild('refChild') child: any;
ngAfterContentInit() {
console.log('ngAfterContentInit');
console.log(this.child);
}
}
应用程序- children
import { Component} from '@angular/core';
@Component({
selector: '应用程序- children ',
template: `
<div #refChild>
<h1>Child headline</h1>
<h2>Child subheadline</h2>
</div>
`
})
export class ChildComponent {}