2017-03-29 12 views
3

@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'; 
     } 
    } 
+0

AFAIRは動作しません。すでにリファレンスがあるコンポーネントを作成した場合、そのコンポーネントを照会する必要はありますか? –

+0

私は@ViewChildrenを使用して、ダイナミックコンポーネント内の**ハイライトディレクティブ**を問い合わせます** – cgatian

+0

'element.nativeElement ... 'の代わりに' @HostBinding() 'を使用してスタイルを設定してください。 –

答えて

3

@ViewChildrenは、子コンポーネント内に含まれるビューではなく、独自のビューのみを照会するため、これは機能しません。動的コンポーネントは、独自のビューを持つ子コンポーネントです。

これを回避するには、出力イベントを持つ動的コンポーネントに@ViewChildrenというクエリを追加して、気になる人(親コンポーネント)に新しいインスタンスが存在することを知らせることができます。

+0

これは最も理にかなっており、最も明白です。 – cgatian

関連する問題