angular - 单击 *ngFor 时注入(inject)组件

标签 angular dynamic

我已按照 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/

相关文章:

Angular - 对象作为选择选项值

javascript - &lt;script&gt; 动态脚本加载问题 - 奇怪的行为

html - 隐藏的可滚动 div,应该适用于所有浏览器

javascript - 换行和5个新空格的正则表达式

angular - PrimeNG 数据表验证

c - C中struct的动态分配

dynamic - 如何在GDB中自动打印接下来的N行执行?

PHP MYSQL动态选择框

Php动态菜单栏代码错误

angular - 使用 Angular 组件样式在 sass 中 Font Awesome 内容