4. 부모 컴포넌트는 프로퍼티 바인딩을 통해 자식 컴포넌트에게 상태 전달
자식 컴포넌트는 @Input 데코레이터로 상태 바인딩
@Input Decorator
<child [info]=“info"></child>
@Input() info: string;
Parent
Component
Child
Component
5. set(), get() 메소드 활용
@Input 데코레이터를 사용하여 부모 컴포넌트로 부터 상태가 전달되고
자식 컴포넌트에 바인딩될 때 상태 정보를 처리할 수 있다.
@Input Decorator
@Input()
set info(info: any) {
// set some value
}
get info() {
return this.info;
}
6. 자식 컴포넌트는 @Output 데코레이터와 EventEmitter를 통해 부모 컴
폰넌트에 이벤트를 방출(emit) 한다.
부모 컴포넌트는 이벤트 바인딩을 통해 전달된 상태를 수신한다.
@Ouput Decorator
Parent
Component
Child
Component
@Output() event = new EventEmitter<any>();
doSomething(info) {
this.event.emit(info)
}
<child (event)=“eventHandler($event)”></child>
eventHandler($event) {
// handle $event
}
7. 부모 컴포넌트에서 직접 자식 컴포넌트의 요소에 접근한다.
ViewChild: 컴포넌트 템플릿에 선언된 자식 컴포넌트의 요소
@ViewChild
Parent
Component
Child
Component
@ViewChild(childComponent) child: ChildComponent;
부모 컴포넌트가 child를 통해 자식 컴포넌트의
프로퍼티와 메소드에 접근한다.
8. Child
Component
Child
Component
부모 컴포넌트에서 직접 자식 컴포넌트의 요소에 접근하는 것은
@ViewChild와 동일
하나 이상의 자식 컴포넌트에 접근할 수 있다.
@ViewChildren
Parent
Component
Child
Component
@ViewChildren(childComponent) children:
QueryList<ChildComponent>;
부모 컴포넌트가 child를 통해 자식 컴포넌트의
프로퍼티와 메소드에 접근한다.
부모 컴포넌트에서 바인딩 할 프로퍼티 타입은
QueryList가 된다.
9. @ViewChild와 @ViewChildren 데코레이터는 부모 컴포넌트에서 자식
컴포넌트의 요소를 가져올 수 있을 뿐만 아니라 템플릿 참조 변수의 요소
도 가져 올 수 있다.
Template reference
<div #header>head</div>
<p #content>content</p>
<div #footer>footer</div>
@ViewChildren('header', 'content', 'footer') elements:QueryList<ElementRef>;
@ViewChild('header') header:ElementRef;
10. 부모 컴포넌트의 템플릿 일부를 자식 컴포넌트의 컨텐츠로 전달한다.
자식 컴포넌트는 ng-content 디렉티브를 통해 위치를 지정한다.
Content Projection
Parent
Component
Child
Component
<child>
<div>parent to child</div>
</child>
<div>some contents</div>
<ng-content></ng-content>
<div>some contents</div>
11. 전달할 템플릿이 하나 이상이고 각각 위치를 조정해야 할 경우에는 select
속성을 이용한다.
Content Projection
Parent
Component
Child
Component
<child>
<div class="third">third template</div>
<div class="second">second template</div>
<header>first template</header>
</child>
<div>some contents</div>
<ng-content select="header"></ng-content>
<ng-content select=".second"></ng-content>
<ng-content select=".third"></ng-content>
<div>some contents</div>
12. ViewChild의 시작 태그와 종료 태그 사이에 있는 컨텐츠를
@ContentChild라고 한다.
부합하는 조건이 1가지 이상일 때는 @ContentChildren을 사용한다.
ngAfterContentInit() 메소드가 호출되는 시점에서 참조하는 것이 안전
하다.
@ContentChild
ItemList
Component
item
Component
@ContentChild('third') thirdContent: ItemComponent;
@ContentChildren() itemsContent: QueryList<ItemComponent>;
ngAfterContentInit(){
//something...
}
<div>some div</div>
<ng-content></ng-content>
<div>some div</div>
<item-list>
<item></item>
<item></item>
<item #third></item>
<item></item>
</item-list>