[Angular]@ViewChild로 자식 컴포넌트 제어
앞서 @Input(), @Output 데코레이터를 사용하여 부모-자식 컴포넌트 간에 데이터를 공유하는 방법을 학습했다. 이번에는 데이터를 공유할 뿐만 아니라 부모 컴포넌트에서 자식 컴포넌트를 직접 제어할 수 있는 @ViewChild에 대해서 알아보자. 여기서 제어할 수 있는 영역은 컴포넌트, DOM, Directive 등이 있다.
ViewChild란 부모 컴포넌트 템플릿 안에 있는 자식 요소들을 의미한다.
<div class="bookSearch-outer">
<div class="d-flex align-items-center p-3 my-3 text-white-50 bg-purple rounded box-shadow">
<img class="mr-3" src="assets/images/search-icon.png" alt="" width="48" height="48">
<div class="lh-100">
<h5 class="mb-0 text-white lh-100">Search Result : </h5>
</div>
</div>
<div class="example-container">
<mat-form-field>
<mat-select placeholder="도서종류" #bookCategorySelect [(ngModel)]="selectedValue" (ngModelChange)="changeValue(bookCategorySelect.value)">
<mat-option *ngFor="let category of bookCaterory" [value]="category.value"> </mat-option>
</mat-select>
</mat-form-field>
<button mat-raised-button color="primary" (click)="clearCondition()">검색 초기화</button>
</div>
<div>
<app-search-box [bookCategory]="displayCategoryName" (searchEvent)="changeTitleBar($event)"></app-search-box>
</div>
<div>
<app-detail-box></app-detail-box>
</div>
<div>
<app-list-box></app-list-box>
</div>
</div>
import {Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { SearchBoxComponent } from "../search-box/search-box.component";
@Component({
selector: 'app-book-search-main',
templateUrl: './book-search-main.component.html',
styleUrls: ['./book-search-main.component.css', './offcanvas.css']
})
export class BookSearchMainComponent implements OnInit {
selectedValue = null;
displayCategoryName = null;
bookCaterory = [
{value: 'all', viewValue: '국내외도서'},
{value: 'country', viewValue: '국내도서'},
{value: 'foreign', viewValue: '국외도서'} ];
searchTitle = null;
constructor() { }
ngOnInit() { }
changeValue(category: string): void {
for(let element of this.bookCaterory ) {
if(element.value == category) {
this.displayCategoryName = element.viewValue;
}
}
}
changeTitleBar(searchInfo) : void {
this.searchTitle = `${searchInfo.keyword} ( ${searchInfo.category} )`;
} }
@ViewChild(SearchBoxComponent) searchComp: SearchBoxComponent;
@ViewChildren(SearchBoxComponent) searchCompArr: QueryList<SearchBoxComponent>;
clearCondition(): void { this.selectedValue = null; this.searchTitle = null;
/*
@ViewChild를 사용할 경우
this.searchComp._bookCategory = null;
this.searchComp.keyword = null;
*/
// @ViewChildren을 사용할 경우
this.searchCompArr.toArray()[0]._bookCategory = null;
this.searchCompArr.toArray()[0].keyword = null;
}
}
https://www.saichoi.com/spice9784/
