【问题标题】:Angular2 Dart - get child elements of componentAngular2 Dart - 获取组件的子元素
【发布时间】:2016-06-04 20:08:49
【问题描述】:

我有一个名为 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. 是否需要做一些特别的事情来获取&lt;item&gt;&lt;/item&gt; 之间的文本,或者@ViewChild 是否会为此工作?

更新:更改模板以包含&lt;ng-content&gt;&lt;/ng-content&gt;

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

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

标识符、标题、城市、城镇、地址、邮政、清除搜索

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

【问题讨论】:

  • 请检查Item 组件是否被实例化。如果元素没有升级到实际的 Angular 组件,则无法查询 Item

标签: angular dart angular-dart


【解决方案1】:

应该是

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

另见https://stackoverflow.com/a/35209681/217408

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

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

Plunker example

【讨论】:

  • 我现在已经完全一样了,它仍在打印[]
  • print(items) 仍在打印出[]print(items.length) 正在打印出0,因此这些项目仍未进入 ButtonSearch 类。我要做的是获取Item 类型的所有子项的 Dart 列表表示,以便我可以执行 print(item.type)print(item.content) 之后我期待在我的控制台中列出 @987654343 @, title, ..., clear &lt;ng-content&gt; 正在打印出项目内的所有文本,所以至少我确定我正在查看的搜索按钮确实有项目。
  • Plunker example 在 TypeScript 中,但应该很容易翻译。也许您在使用它的directives 中缺少Item 类。
  • 啊,不知道我必须在两个地方添加Item 指令。这解决了它:-D
  • 您只需要在一个地方使用它来执行示例中的指令。无需将它们添加到ButtonSearch 组件中的directives
猜你喜欢
  • 1970-01-01
  • 2016-10-04
  • 2017-05-07
  • 1970-01-01
  • 2017-12-03
  • 1970-01-01
  • 2013-08-21
  • 2016-06-30
  • 2017-05-26
相关资源
最近更新 更多