【问题标题】:Inject component on click in a *ngFor单击 *ngFor 时注入组件
【发布时间】:2017-02-23 21:17:05
【问题描述】:

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

【问题讨论】:

    标签: angular dynamic


    【解决方案1】:

    我会使用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

    【讨论】:

    • 谢谢一堆!真的很好解释!.. PersonInjectorDirective 是否有任何优点/缺点?
    • 我认为如果你经常使用它是合理的。特别是如果您使用 PersonInjectorDirective 这样的类型来表示应用程序的某些架构部分之间的关​​系。许多团队都遵循这种方法github.com/angular/material2/blob/master/src/lib/core/portal/…
    猜你喜欢
    • 2016-11-04
    • 2017-06-17
    • 2020-05-25
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多