2017-02-23 5 views
2

私はオーバーhttps://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.htmlのチュートリアルに従っているとうまく:)を注入*のクリックでコンポーネントngFor

作業it'sは、今私は、もう少し高度なことをやりたいです。 http://plnkr.co/edit/D1q7Al60m4UK1weRlcmQ?p=preview

名前をクリックすると、別の行の下に詳細が表示されます。

例えば、 「Luke Skywalker」または「C3PO」をクリックすると、1行目と2行目の間に行が作成され、詳細が表示されます。

"product-host"属性を動的に追加しようとしましたが、ディレクティブが属性の存在を期待しているため動作しませんでした。

<div *ngFor="let person of persons.results" fxFlex="50%" fxFlex.gt-sm="33%" person-host> 

答えて

3

私はこれを達成するためにViewChildrenを使用します。

1)ちょうどあなたのshowPerson機能でインデックスを渡す

テンプレート

<div *ngFor="let person of persons.results; let i = index" fxFlex="50%" fxFlex.gt-sm="33%" person-host> 
    <md-card (click)="showPerson(person, i)">{{person.name}}</md-card> 
</div> 

および情報カードのための所望の場所を決定するためにそれを使用

コンポーネント:2つの方法があります。

activatedViewContainerRef: ViewContainerRef; 

@ViewChildren(PersonInjectorDirective) personHosts: QueryList<PersonInjectorDirective>; 

loadPerson(person, index) { 
    if(this.activatedViewContainerRef) { 
    this.activatedViewContainerRef.clear(); 
    } 
    let componentFactory = this._componentFactoryResolver.resolveComponentFactory(PersonComponent); 
    this.activatedViewContainerRef = this.personHosts.find((item, i) => i === index).viewContainerRef; 

    let componentRef = this.activatedViewContainerRef.createComponent(componentFactory); 
    (<PersonComponent>componentRef.instance).person = person; 
} 

showPerson(person, index: number) { 
    this.loadPerson(person, index % 2 ? index : index + 1); 
} 

ngOnDestroy() { 
    if(this.activatedViewContainerRef) { 
    this.activatedViewContainerRef.clear(); 
    } 
} 

Plunker Example

2)またPersonInjectorDirectiveせずにそれを構築することができます。

<div *ngFor="let person of persons.results; let i = index" fxFlex="50%" fxFlex.gt-sm="33%" #refs> 
    <md-card (click)="showPerson(person, i)">{{person.name}}</md-card> 
</div> 

と、次のようにViewChildren式を変更:

@ViewChildren('refs', { read: ViewContainerRef}) personHosts: QueryList<ViewContainerRef>; 

Plunker Example

+0

Thxを束をこの場合、あなたはテンプレート変数(#refs)を宣言する必要があります!本当にきちんと説明されました!.. PersonInjectorDirectiveとの賛否両論はありますか? – Mackelito

+1

しばしばそれを使用すれば妥当だと思います。特に、アプリケーションのいくつかのアーキテクチャ部分の間の関係のために 'PersonInjectorDirective'のような型を使用する場合。多くのチームがこのアプローチを採用しています。https://github.com/angular/material2/blob/master/src/lib/core/portal/portal-directives.ts#L28 – yurzui

関連する問題