有谁知道如何迭代Angular 2 ng内容项?
我需要检查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注入light DOM的内容即可
ParentComponent implements AfterContentInit{ @ContentChildren(ChildComponent) contents : QueryList<ChildComponent>; ngAfterContentInit() { //access contents here } }