我會用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>
,然後用它來確定信息卡所需的地方
組件
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
。在這種情況下,你需要聲明模板變量(#refs
):
<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一堆!真的很好解釋!..是否有PersonInjectorDirective的優點/缺點? – Mackelito
我想如果你經常使用它,那麼這是合理的。特別是如果您使用'PersonInjectorDirective'這樣的類型來處理應用程序的某些架構部分之間的關系。許多團隊堅持這種方法https://github.com/angular/material2/blob/master/src/lib/core/portal/portal-directives.ts#L28 – yurzui