私はこれを達成するために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
Thxを束をこの場合、あなたはテンプレート変数(
#refs
)を宣言する必要があります!本当にきちんと説明されました!.. PersonInjectorDirectiveとの賛否両論はありますか? – Mackelitoしばしばそれを使用すれば妥当だと思います。特に、アプリケーションのいくつかのアーキテクチャ部分の間の関係のために 'PersonInjectorDirective'のような型を使用する場合。多くのチームがこのアプローチを採用しています。https://github.com/angular/material2/blob/master/src/lib/core/portal/portal-directives.ts#L28 – yurzui