[英]Access nested content children
@Directive({
selector: '[some-directive]'
})
export class SomeDirective...
@Component({
selector: 'inner-component',
template: `
<div some-directive></div>
`
})
export class InnerComponent {
}
@Component({
template: `
<inner-component></inner-component>
`
})
export class OuterComponent {
@ContentChildren(SomeDirective, {descendants: true}) elementsWithDirective: QueryList<SomeDirective>;
}
這是獲得這些指令的正確方法嗎? elementsWithDirective
返回空結果數組。 我無法以這種方式訪問它。 我唯一可以解決此問題的方法是將<div app-some-directive></div>
直接放在OuterComponent的視圖內,但我想避免這種情況。
似乎您對contentChildren和viewChildren感到困惑。 在您的情況下,應使用viewChildren在InnerComponent中查詢SomeDirective,並將結果發送到OuterComponent,例如
@Component({
selector: 'outer-component',
template: ` <inner-component
(elementsWithDirectiveChanges)="elementsWithDirectiveChanged($event)">
</inner-
component>`
})
export class OuterComponent {
elementsWithDirectiveChanged(change: any) {
console.log(change);
}
}
@Component({
selector: 'inner-component',
template: `
<div some-directive>inner</div>
`
})
export class InnerComponent {
@ViewChildren(SomeDirective) elementsWithDirective!: QueryList<SomeDirective>;
@Output() elementsWithDirectiveChanges = new EventEmitter();
ngAfterViewInit() {
this.elementsWithDirectiveChanges.emit(this.elementsWithDirective);
}
}
演示https://stackblitz.com/edit/angular-2oesig?file=src%2Fapp%2Fhello.component.ts
AFAIK當前無法直接從組件中獲取孫元素。 我不知道您的用例是什么,但是您可以:
@ViewChild(InnerComponent) innerComponent: InnerComponent
到外部組件 @ViewChild(SomeDirective) someDirective: SomeDirective
到內部組件 ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }
內部組件訪問您的指令ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }
ngAfterViewInit(): void { console.log(this.innerComponent.someDirective); }
這里的閃電戰
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.