[Angular Tutorial 04] Master/Detail Components
본문 바로가기

Interests [관심사]/Angular

[Angular Tutorial 04] Master/Detail Components

[Angular Tutorial 04] Master/Detail Components

 https://angular.io/tutorial/toh-pt3


현재 HeroesComponent 는 list 부분과 detail 부분을 함께 출럭 하고있습니다. 

list 와 detail 은 분명히 다른 역할을 하는 부분이기 때문에 우리는 detail component 를 생성하여 view 를 분할하도록 할 예정입니다.

다음 명령어를 통하여 hero-detail component 를 생성 합니다.


 ng generate component hero-detail 



CLI 를 통해 component 를 생성하면 4 개의 파일이 기본적으로 생성 됩니다.


A CSS file for the component styles.

An HTML file for the component template.

A TypeScript file with a component class named HeroDetailComponent.

A test file for the HeroDetailComponent class.


component 가 잘 생성이 되었다면, 우리는 src/app/hero-detail/hero-detail.component.html 파일을 다음과 같이 수정 합니다.


<div *ngIf="hero">
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name" />
</label>
</div>
</div>


기존의 출력되던 *ngIf 의 값이 변경된 것이 눈에 띕니다.

그렇다면 우리는 hero-detail.component.ts 를 손 봐야 할 것입니다.



Add the @Input() hero property

The HeroDetailComponent template binds to the component's hero property which is of type Hero.

Open the HeroDetailComponent class file and import the Hero symbol.


src/app/hero-detail/hero-detail.component.ts (import Hero) 파일에 hero.ts 파일을 import 합니다. 확장자는 생략 합니다.

그리고 우리는 angular core의 기능인 Input 사용을 위하여 Input 역시 import 시킵니다.

@Input() hero: Hero; 를 선언합니다. (component간에 값을 전달할 수 있게 해주는 decorator)

input decorator(@input)가 붙은 class의 항목은 html에서 해당 component를 호출할때 값을 전달 받을 수 있습니다. <selector_이름 [input_항목_이름]="값"></selector_이름>의 형태로 호출하면 input_항목_이름에 값이 전달됩니다.

출처 : https://www.a-mean-blog.com/ko/blog/Angular-2/Tour-of-Heroes/Multiple-Components-input


import { Component, OnInit, Input } from '@angular/core'; // Input 추가
import { Hero } from '../hero'; //hero 추가

@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

@Input() hero: Hero;
constructor() { }

ngOnInit() {
}

}


이제 HeroDetailComponent를 출력시킬 차례 입니다.

heroes.component.html 에 다음과같이 detail 이 있던 자리에 view 를 추가 합니다.

리스트 부분도 살짝 변경이 되었습니다.


<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>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>



기능상 변경 된 사항은 없으나, Heroes component 안에 Detail Component 가 속해있는 구조로 변경 되었습니다



You created a separate, reusable HeroDetailComponent.

You used a property binding to give the parent HeroesComponent control over the child HeroDetailComponent.

You used the @Input decorator to make the hero property available for binding by the external HeroesComponent.