2017-02-23 28 views
2

我已經過在https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html跟着教程和it's工作得很好:)進樣組件在* ngFor

現在我想這樣做更高級一點。 http://plnkr.co/edit/D1q7Al60m4UK1weRlcmQ?p=preview

我想要的是點擊一個名字應該打開一個單獨的行下方的細節。

例如。點擊「Luke Skywalker」或「C3PO」應在第一行和第二行之間創建一行並顯示詳細信息。

我試圖動態地添加「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> 

,然後用它來確定信息卡所需的地方

組件

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

+0

THX一堆!真的很好解釋!..是否有PersonInjectorDirective的優點/缺點? – Mackelito

+1

我想如果你經常使用它,那麼這是合理的。特別是如果您使用'PersonInjectorDirective'這樣的類型來處理應用程序的某些架構部分之間的關​​系。許多團隊堅持這種方法https://github.com/angular/material2/blob/master/src/lib/core/portal/portal-directives.ts#L28 – yurzui