@ViewChildrenを含む親コンポーネントは、動的に作成されるコンポーネントの結果を返しません。ViewChildren動的コンポーネントが見つかりません
コンテナコンポーネントにはhighlight
ディレクティブが含まれ、動的に生成されたコンポーネントにはテンプレート内にhighlight
ディレクティブが含まれています。 @ViewChildren
と照会すると、クエリの長さはに戻ります。予想される結果はです。
HTMLから分かるように、DOMには2つの強調表示があります。
<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';
}
}
AFAIRは動作しません。すでにリファレンスがあるコンポーネントを作成した場合、そのコンポーネントを照会する必要はありますか? –
私は@ViewChildrenを使用して、ダイナミックコンポーネント内の**ハイライトディレクティブ**を問い合わせます** – cgatian
'element.nativeElement ... 'の代わりに' @HostBinding() 'を使用してスタイルを設定してください。 –