包含@ViewChildren的父组件不会返回动态创建的组件的结果。
容器组件包含一个highlight指令,动态生成的组件在其模板中包含一个highlight指令。使用@ViewChildren查询时,查询长度返回1。预期的结果是2。
从HTML中可以看到,DOM上肯定有两个突出显示的指令。
<container-component>
<div></div>
<dynamic-component ng-version="4.0.0">
<div highlight="" style="background-color: yellow;">Dynamic!</div>
</dynamic-component>
<div highlight="" style="background-color: yellow;">Number of Highlights
<div></div>
</div>
</container-component>我是不是遗漏了什么?
https://plnkr.co/edit/LilvHJgFjPHnPuaNIKir?p=preview
容器组件
@Component({
selector: 'container-component',
template: `
<div #contentProjection></div>
<div highlight>Number of Highlights {{highlightCount}}<div>
`,
})
export class ContainerComponent implements OnInit, AfterViewInit {
@ViewChildren(HighlightDirective) private highlights: QueryList<HighlightDirective>;
@ViewChild('contentProjection', { read: ViewContainerRef }) private contentProjection: ViewContainerRef;
constructor(
private resolver: ComponentFactoryResolver
) {
}
ngOnInit() {
this.createDynamicComponent();
}
ngAfterViewInit() {
console.log(this.highlights.length);
// Should update with any DOM changes
this.highlights.changes.subscribe(x => {
console.log(this.highlights.length);
});
}
private createDynamicComponent(){
const componentFactory = this.resolver.resolveComponentFactory(DynamicComponent);
this.contentProjection.createComponent(componentFactory);
}
}动态组件
@Component({
selector: 'dynamic-component',
template: `
<div highlight>Dynamic!</div>
`,
})
export class DynamicComponent {
}高亮指令
@Directive({
selector: '[highlight]'
})
export class HighlightDirective {
constructor(private elementRef: ElementRef) {
elementRef.nativeElement.style.backgroundColor = 'yellow';
}
}发布于 2017-03-29 19:33:14
这不起作用,因为@ViewChildren只查询自己的视图,而不查询子组件中包含的视图。动态组件是具有自己的视图的子组件。
为了解决这个问题,您可以在动态组件中添加一个@ViewChildren查询,该组件具有一个输出事件,让任何关心它的人(您的父组件)都知道存在一个新实例。
https://stackoverflow.com/questions/43102427
复制相似问题