我已按照 https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html 上的教程进行操作而且运行得很好:)
现在我想做更高级的事情。 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>
最佳答案
我会使用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
关于angular - 单击 *ngFor 时注入(inject)组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42415203/