ViewChildren找不到动态组件 [英] ViewChildren not finding Dynamic Components
问题描述
包含@ViewChildren的父组件不会返回动态创建的组件的结果.
A parent component that contains a @ViewChildren is not returning results for components that are created dynamically.
容器组件包含一个highlight
指令,而动态生成的组件在其模板中包含一个highlight
指令.用@ViewChildren
查询时,查询长度返回 1 .预期结果为 2 .
The container component contains a highlight
directive, and the dynamically generated component contains a highlight
directive within it's template. When queried with @ViewChildren
the query length returns 1. The expected result is 2.
从HTML中可以看到,在DOM上肯定有两个高亮指令.
As you can see from the HTML there are definitely two highlight directives on the 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';
}
}
推荐答案
这不起作用,因为@ViewChildren
仅查询自己的视图,而不查询子组件中包含的视图.动态组件是具有自己视图的子组件.
That doesn't work because @ViewChildren
only queries its own view, not the view contained within child components. Your dynamic component is a child component that has its own view.
要解决此问题,您可以在动态组件中添加一个具有输出事件的@ViewChildren
查询,以使任何在乎的人(您的父组件)都知道新实例的存在.
To get around this you could add a @ViewChildren
query in the dynamic component that has an output event to let anyone who cares (your parent component) know that a new instance exists.
这篇关于ViewChildren找不到动态组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!