angular – 从ng-content访问@ViewChild模板

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

app组件:

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

表列组件:

@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...
  });      
}

Plunker

我使用不同的生命周期钩子(ngOnInit,ngAfterViewInit)来定义问题…

如果你想在Light DOM中搜索,那么你需要使用@ContentChild并等到ngAfterContentinit挂钩
@ContentChild('template') template;  

ngAfterContentinit() {
  console.log(this.template);
});

也可以看看

> What’s the difference between @ViewChild and @ContentChild?

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...