출처 : https://angular.kr/tutorial/toh-pt2
// src/app/mock/index.js
import { HSModel } from '../model';
export const HEROES: HSModel.Hero[] = [
{ id: 11, name: 'Dr Nice' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' },
];
*ngFor
를 사용한다.
항목을 반복하는 Angular 디렉티브 입니다. 이 디렉티브는 목록에 있는 항목마다 호스트 엘리먼트를 반복합니다.
// src/app/component/heroes/heroes.component.html
<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>
상기 코드에서 (click)="onSelect(hero)"
에 해당하는 코드를 작성해준다.
앱이 실행되는 시점에는 selectedHero 는 빈값이기에 ?:
및 *ngIf
를 사용한다.
// src/app/component/heroes/heroes.component.ts
export class HeroesComponent implements OnInit {
heroes: HSModel.Hero[] = Mock.HEROES;
selectedHero?: HSModel.Hero;
constructor() {}
ngOnInit(): void {}
onSelect(hero: HSModel.Hero): void {
this.selectedHero = hero;
}
}
// src/app/component/heroes/heroes.component.html
<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>
<div *ngIf="selectedHero">
<h2>{{ selectedHero.name | uppercase }} Details</h2>
<div><span>id: </span>{{ selectedHero.id }}</div>
<div>
<label for="hero-name">Hero name: </label>
<input id="hero-name" [(ngModel)]="selectedHero.name" placeholder="name" />
</div>
</div>
특정 조건에 따라 CSS 클래스를 추가하거나 제거할 수 있습니다.
[class.some-css-class]="some-condition"
[class.클래스 이름]="(참or거짓)조건"
[class.selected]="hero === selectedHero"
hero === selectedHero 가 참이면 selected 라는 class 가 추가된다.