有谁知道如何迭代 Angular 2 ng-content 项目?
我需要检查 ng-content 中存在的项目定义的属性值是什么。有谁知道如何获得它们?
最好的方案是获取其中的实际组件实例,因为我可以在组件内部设置一些内部属性并直接访问它们会很棒!
一些示例代码:
// ====================== Container Component =======================
import * as ng from "angular2/angular2";
@ng.Component({
selector: 'grid-layout',
lifecycle: [ng.onInit]
})
@ng.View({
templateUrl: `<div><ng-content></ng-content></div>`
})
export class GridLayout
{
constructor(){
}
private onInit(): void {
// ??? something like this.ngContent would be great :)
}
}
// ====================== Caller Component =======================
import * as ng from "angular2/angular2";
@ng.Component({
selector: 'my-page'
})
@ng.View({
templateUrl: `
<grid-layout>
<div data-att1="container 1">1</div>
<div data-att2="container 2">2</div>
<div>3</div>
</grid-layout>`,
directives:[GridLayout]
})
export class MyPage
{
constructor(){
}
}
最佳答案
只需使用@ContentChildren 注入(inject)light DOM 的内容
ParentComponent implements AfterContentInit{
@ContentChildren(ChildComponent) contents : QueryList<ChildComponent>;
ngAfterContentInit()
{
//access contents here
}
}
关于typescript - 如何迭代 Angular 2 ng-content 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708366/