在没有包装器 ViewChild 的情况下从组件代码访问 ng-content
Accessing ng-content from component code without a wrapper ViewChild
假设我有一个名为 RecursiveComponent 的组件(带有一个名为 recursive 的选择器)。它有一个数字 "identifier" 作为输入,并在其主体中接受更多的 RecursiveComponents。所以使用该组件的 HTML 代码可能如下所示:
<recursive identifier="1">
<recursive identifier="2">
<recursive identifier="3"></recursive>
</recursive>
<recursive identifier="4"></recursive>
</recursive>
为简单起见,组件只输出“identifier has x children”,然后是通过[=12完成的插入主体=].这行得通,但要弄清楚有多少子组件,我必须用 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.
假设我有一个名为 RecursiveComponent 的组件(带有一个名为 recursive 的选择器)。它有一个数字 "identifier" 作为输入,并在其主体中接受更多的 RecursiveComponents。所以使用该组件的 HTML 代码可能如下所示:
<recursive identifier="1">
<recursive identifier="2">
<recursive identifier="3"></recursive>
</recursive>
<recursive identifier="4"></recursive>
</recursive>
为简单起见,组件只输出“identifier has x children”,然后是通过[=12完成的插入主体=].这行得通,但要弄清楚有多少子组件,我必须用 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.