首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >@ContentChildren不拾取自定义组件中的项

@ContentChildren不拾取自定义组件中的项
EN

Stack Overflow用户
提问于 2018-12-06 14:26:34
回答 2查看 2.3K关注 0票数 8

我正在尝试使用@ContentChildren来拾取所有带有#buttonItem标签的项目。

代码语言:javascript
复制
@ContentChildren('buttonItem', { descendants: true })

当我们在父组件中直接拥有ref项时,这是有效的。

代码语言:javascript
复制
<!-- @ContentChildren returns child item -->
<parent-component>
  <button #buttonItem></button>
<parent-component>

但是,如果包含#buttonItem引用的元素包装在自定义组件中,即使我设置了{descendants: true}选项,@ContentChildren也不会选择它。

代码语言:javascript
复制
<!-- @ContentChildren returns empty -->
<parent-component>
  <child-component-with-button-ref></child-component-with-button-ref>
<parent-component>

我已经创建了一个简单的StackBlitz example来演示这一点。

EN

回答 2

Stack Overflow用户

发布于 2020-07-08 23:13:43

我也有同样的问题。我们正在为angular使用Kendo组件。需要将列定义为网格组件的ContentChilds。当我想把它包装到一个自定义组件中,并试图通过ng-content提供额外的列时,它根本不起作用。

通过重置自定义包装组件的网格组件AfterViewInit的QueryList,我设法使其正常工作。

代码语言:javascript
复制
  @ViewChild(GridComponent, { static: true })
  public grid: GridComponent;

  @ContentChildren(ColumnBase)
  columns: QueryList<ColumnBase>;

  ngAfterViewInit(): void {
    this.grid.columns.reset([...this.grid.columns.toArray(), ...this.columns.toArray()]);
    this.grid.columnList = new ColumnList(this.grid.columns);
  }
票数 2
EN

Stack Overflow用户

发布于 2020-05-12 06:03:00

一种选择是重新绑定到content子级。

在您要添加要拾取的内容子项的模板中:

代码语言:javascript
复制
<outer-component>
  <content-child [someBinding]="true" (onEvent)="someMethod($event)">
      e.g. inner text content
  </content-child>
</outer-component>

在示例虚构的<outer-component>内部

代码语言:javascript
复制
@Component()
class OuterComponent {
  @ContentChildren(ContentChild) contentChildren: QueryList<ContentChild>;
}

和用于添加<content-child>组件的<outer-component>模板,重新绑定到它:

代码语言:javascript
复制
<inner-template>
  <content-child
    *ngFor="let child of contentChildren?.toArray()"
    [someBinding]="child.someBinding"
    (onEvent)="child.onEvent.emit($event)"
  >
      <!--Here you'll have to get the inner text somehow-->
  </content-child>
</inner-template>

根据您的情况,获取内部文本可能是不可能的。如果您拥有对虚构的<content-child>组件的完全控制,则可以公开对元素ref的访问:

代码语言:javascript
复制
@Component()
class ContentChildComponent {
  constructor(public element: ElementRef<HTMLElement>)
}

然后,当您重新绑定到它时,您可以添加[innerHTML]绑定:

代码语言:javascript
复制
<content-child
  *ngFor="let child of contentChildren?.toArray()"
  [someBinding]="child.someBinding"
  (onEvent)="child.onEvent.emit($event)"
  [innerHTML]="child.element.nativeElement.innerHTML"
></content-child>

但是,您可能必须通过sanitize the input连接到[innerHTML]

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53645733

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档