假设我有一个名为 RecursiveComponent 的组件(带有一个名为 recursive 的选择器)。它有一个数字“标识符”作为输入,并在其主体中接受更多的 RecursiveComponents。所以使用该组件的 HTML 代码可能如下所示:
<recursive identifier="1">
<recursive identifier="2">
<recursive identifier="3"></recursive>
</recursive>
<recursive identifier="4"></recursive>
</recursive>
为简单起见,该组件仅输出“identifier has x children”,然后是通过 <ng-content>
完成的插入主体.这行得通,但要弄清楚有多少子组件,我必须用 ViewChild 包装 ng-content 并查看 nativeElement 的 childNodes,我觉得这有点矫枉过正。这是组件代码的样子:
@Component({
selector: 'recursive',
template: `
{{identifier}} has {{noOfChildren}} children
<div #contentRef>
<ng-content select="recursive"></ng-content>
</div>`
})
export class RecursiveComponent implements OnChanges {
@ViewChild('contentRef', { read: ElementRef }) contentRef: ElementRef;
@Input() identifier: number;
noOfChildren: number;
ngOnChanges() {
if (this.contentRef) {
this.noOfChildren = this.contentRef.nativeElement.childNodes.length;
}
}
}
是否有更好、更像 Angular 的方式来从组件代码中访问 ng-content?这感觉像是黑客攻击。
最佳答案
我认为这可能是您可以执行此类操作的唯一方法,您需要访问 DOM 中的元素。然而,还有另一种(可能更好的)方法可以使用@ViewChildren 来做到这一点。
You can use ViewChildren to get the QueryList of elements or directives from the view DOM. Any time a child element is added, removed, or moved, the query list will be updated, and the changes observable of the query list will emit a new value.
关于angular - 在没有包装器 ViewChild 的情况下从组件代码访问 ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52149483/