@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的视图内,但我想避免这种情况。
答案 0 :(得分:1)
似乎您对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