从ng-content访问@ViewChild模板

Iev*_*nov 10 angular

是否可以将模板与ng-content结合使用,如下所述:

应用组件:

<table-column>
  <template #template let-item="item">
    <input type="text" [(ngModel)]="item.foo" />
  </template>
</table-column>
Run Code Online (Sandbox Code Playgroud)

表列组件:

@Component({
  selector: 'table-column',
  template: '<ng-content></ng-content>'
})
export class TableColumnComponent implements OnInit {
  @ViewChild('template') template;  

  ngOnInit() {
    console.log(this.template); // undefined
    // create column object with template and different metadata...
  });      
}
Run Code Online (Sandbox Code Playgroud)

Plunker

undefined使用不同的生命周期钩子(ngOnInit,ngAfterViewInit)得到的问题......

yur*_*zui 17

如果你想在Light DOM中搜索,那么你需要使用@ContentChild并等到ngAfterContentInit挂钩

@ContentChild('template') template;  

ngAfterContentInit() {
  console.log(this.template);
}); 
Run Code Online (Sandbox Code Playgroud)

也可以看看