【问题标题】:ContentChild not working via QueryTemplate and Component referenceContentChild 无法通过 QueryTemplate 和组件参考工作
【发布时间】:2019-09-02 04:55:08
【问题描述】:

我可以投影内容,但无法获得相同的参考

https://stackblitz.com/edit/angular-khyr1u?file=src%2Fapp%2Fapp.component.html

我尝试使用 #SelectorName 以及使用组件名称 ContentChild() 和 ContentChildren()。 尽管调用了 ngAfterViewInit 钩子,但不知何故我无法获得参考

更新的 plunk 说明:viewchild、viewchildren、contentchild、contentChildren:https://stackblitz.com/edit/angular-wnhayw?file=src/app/course-card/course-card.component.ts

【问题讨论】:

    标签: angular


    【解决方案1】:

    您正在寻找的是 @ViewChild 装饰器,而不是 @ContentChild 装饰器。

    @ContentChild 装饰器为您提供了对位于组件的开始标记和结束标记之间的元素的引用:

    <my-component>
      <div #myContentChild></div>
    </my-component>
    

    @ViewChild 装饰器为您提供对组件视图中元素的引用:

    my-component.component.html:

    <div #myViewChild></div>
    

    在您的示例中,#test 元素是 my-app 的 view-child 和 &lt;app-course-card&gt; 的 content-child。这意味着如果您想从AppComponent 组件中查询#test,那么您可以使用@ViewChild。如果要从CourseCardComponent 中查询#test,则需要使用@ContentChild

    有关更多详细信息,请参阅以下 SO 帖子:

    What's the difference between @ViewChild and @ContentChild?

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-24
    • 2011-05-24
    • 1970-01-01
    相关资源
    最近更新 更多