如何迭代Angular 2 ng内容项?

jps*_*sfs 4 typescript angular

有谁知道如何迭代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(){

    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*623 5

只需使用@ContentChildren注入light DOM的内容即可

ParentComponent implements AfterContentInit{
  @ContentChildren(ChildComponent) contents : QueryList<ChildComponent>; 

  ngAfterContentInit()
  {
     //access contents here
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 只要孩子是ng2组件,他们都可以从公共基础组件类继承..如果你想知道内容区域(轻DOM区域)中的原生HTML元素(例如div/h1 ..etc),他们可以使用@ContentChildren(ElementRef)内容注入:QueryList <ElementRef> (3认同)