Angular2 Dart - 获取组件的子元素

Angular2 Dart - get child elements of component

我有一个名为 button-search 的组件,它有一个带有搜索选项的下拉菜单:

<button-search> 
    <item type="identifier">Identifier</item>
    <item type="title">Title</item>
    <item type="city">City</item>
    <item type="town">Town</item>
    <item type="address">Address</item>
    <item type="postal">Postal</item>
    <item type="divider"></item>
    <item type="clear">Clear Search</item>
</button-search>

item 组件不应该直接渲染任何东西,而是将复杂的参数传递给 button-search 组件,以便 button-search 组件可以渲染那些下拉项它应该被渲染。

Item定义如下:

@Component(
    selector: 'item',
    template: '')
class Item {

    @Input() String type = "type-goes-here";

}

ButtonSearch定义如下:

@Component(
    selector: 'button-search',
    directives: const[Item],
    template: '''
       ... enormous template ...    
    ''')
class ButtonSearch {

    ButtonSearch(@ViewChildren(Item) QueryList<Item> items){

        print(items);

    }
}

我看到的不是打印到控制台的 9 项列表,而是 []

我试过使用字符串参数而不是对象,但它仍然给我 null。

ButtonSearch(@ViewChildren('item') QueryList<Item> items){
  1. 我缺少什么来制作 @ViewChildren 获取所有项目并打印 []

  2. 以外的内容
  3. 是否需要做一些特殊的事情来获取 <item></item> 之间的文本,或者 @ViewChild 是否可以做到这一点?

更新:更改模板以包含 <ng-content></ng-content>

template: '''
          <ng-content></ng-content>
           ... enormous template ...    
        ''')

我可以看到以下内容作为 button-search 组件的一部分在浏览器中打印:

Identifier, Title, City, Town, Address, Postal, Clear Search

所以至少我知道我所在的页面在其 button-search 组件中确实有项目。

应该是

@Component(
    selector: 'button-search',
    directives: const[Item],
    template: '''
       <ng-content></ng-content>
       ... enormous template ...    
    ''')
class ButtonSearch implements AfterContentInit{
    @ContentChildren(Item) QueryList<Item> items;

    ngAfterContentInit() {
        print(items);
    }    
}

另见

还有 @Query() 注释允许构造函数注入对子元素的引用,但它被标记为已弃用。

<ng-content>
如果您将 "content" 作为子项传递给您的组件,那么您可以使用 @ContentChildren() 而不是 @ViewChildren() 来查询它们。如果您希望它们显示在 DOM 中,您还需要添加 <ng-content></ng-content> 标签作为嵌入的目标。您还可以有多个 <ng-content></ng-content> 标签,其中 select=".someCssSelector" 可用于在特定目标位置嵌入内容子集。不过应该只有一个 <ng-content></ng-content> 没有 select 属性。第一个没有 select 的将定位所有与其他选择器不匹配的内容。

Plunker example