我正在尝试使用@ContentChildren
来拾取所有带有#buttonItem
标签的项目。
@ContentChildren('buttonItem', { descendants: true })
当我们在父组件中直接拥有ref项时,这是有效的。
<!-- @ContentChildren returns child item -->
<parent-component>
<button #buttonItem></button>
<parent-component>
但是,如果包含#buttonItem
引用的元素包装在自定义组件中,即使我设置了{descendants: true}
选项,@ContentChildren
也不会选择它。
<!-- @ContentChildren returns empty -->
<parent-component>
<child-component-with-button-ref></child-component-with-button-ref>
<parent-component>
我已经创建了一个简单的StackBlitz example来演示这一点。
发布于 2020-07-08 23:13:43
我也有同样的问题。我们正在为angular使用Kendo组件。需要将列定义为网格组件的ContentChilds。当我想把它包装到一个自定义组件中,并试图通过ng-content提供额外的列时,它根本不起作用。
通过重置自定义包装组件的网格组件AfterViewInit的QueryList,我设法使其正常工作。
@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);
}
发布于 2020-05-12 06:03:00
一种选择是重新绑定到content子级。
在您要添加要拾取的内容子项的模板中:
<outer-component>
<content-child [someBinding]="true" (onEvent)="someMethod($event)">
e.g. inner text content
</content-child>
</outer-component>
在示例虚构的<outer-component>
内部
@Component()
class OuterComponent {
@ContentChildren(ContentChild) contentChildren: QueryList<ContentChild>;
}
和用于添加<content-child>
组件的<outer-component>
模板,重新绑定到它:
<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的访问:
@Component()
class ContentChildComponent {
constructor(public element: ElementRef<HTMLElement>)
}
然后,当您重新绑定到它时,您可以添加[innerHTML]
绑定:
<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]
。
https://stackoverflow.com/questions/53645733
复制相似问题