Reputation: 1995
I am learning Angular using the "Tour of Heroes" app. In the multiple components part, we can show hero details by clicking on the hero name. What would be the design pattern (or implementation) to have multiple instances of "Hero Details" component, so it is displayed dynamically under each hero, when it is clicked?
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>
`
My goal is to have "my-hero-detail" element in each "li" and then display it with that specific hero details upon clicking on the name.
Upvotes: 0
Views: 1132
Reputation: 96889
You can use <my-hero-detail>
multiple times:
<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>
Then if you want to be able to hide/show the detail you have to update selectedHeroes
to contain true/false values for each hero indicating whether it should be visible or not.
selectedHeroes: Object = {};
See demo: http://plnkr.co/edit/nG0RkwR2kmr6AXzln6mU?p=info
Note that styles are mangled because <li>
doesn't expect to contain <my-hero-detail>
elements.
Upvotes: 1