在 Angular 应用程序中插入同一组件的多个副本

inserting multiple copies of the same component in the Angular application

我正在使用 "Tour of Heroes" 应用学习 Angular。在multiple components part中,我们可以通过点击英雄名称来显示英雄详情。具有多个 "Hero Details" 组件实例的设计模式(或实现)是什么,以便在单击时动态显示在每个英雄下方?

template: `
  <h1>{{title}}</h1>
  <h2>My Heroes</h2>
  <ul class="heroes">
    <li *ngFor="let hero of heroes"
      [class.selected]="hero === selectedHero"
      (click)="onSelect(hero)">
      <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
  </ul>
  <my-hero-detail [hero]="selectedHero"></my-hero-detail>
`

我的目标是在每个 "li" 中包含 "my-hero-detail" 元素,然后在单击名称时显示特定英雄的详细信息。

您可以多次使用<my-hero-detail>

<ul class="heroes">
  <li *ngFor="let hero of heroes; let i=index"
    [class.selected]="hero === selectedHero"
    (click)="selectedHeroes[i] = !selectedHeroes[i]">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
    <my-hero-detail [hero]="hero" [style.display]="selectedHeroes[i] ? 'block' : 'none'"></my-hero-detail>
  </li>
</ul>

然后,如果您希望能够 hide/show 细节,您必须更新 selectedHeroes 以包含每个英雄的 true/false 值,指示它是否应该可见。

selectedHeroes: Object = {};

查看演示:http://plnkr.co/edit/nG0RkwR2kmr6AXzln6mU?p=info

请注意,样式已损坏,因为 <li> 不希望包含 <my-hero-detail> 元素。