dynamic Angular component 관리

dynamic Angular component 관리

컴포넌트를 *ngIf를 통해 관리하며, 생성될 때 자식 컴포넌트 안에 있는 함수를 부모에서 호출하는 상황이 있었다.

문제

@ViewChild('color') color: ColorComponent;

위와 같이 예시가 있다고 하면,

isOpen = true를 한 후 바로 this.color를 호출 했을 때 this.color === undefined가 된다.

아직 color 컴포넌트가 완전히 init되지 않은 시점에 호출을 했기 때문이다.

이를 해결하고자 처음에는 단순히 settimeout을 통해 딜레이를 준 후 init이 되고 컴포넌트를 호출을 했다.

하지만, 이는 프로그래밍 흐름상 옳지 않은 방법이라 생각하였고, 이를 해결할 방법을 찾았다.

solution

@ViewChildren("color") public color: QueryList

this.color.changes.subscribe((compo: QueryList) => {

console.log(color.first)

}

viewChild 대신 viewChildren

QueryList 내부 함수인 changes를 통해 해당 컴포넌트 상태가 변경될 때 호출이 되는 함수를 이용하면 해결이 된다.

이는 color component가 isOpen = true로 되면서 완전 init이 되고 호출이 되기 때문에 this.color는 undefined가 되지않는다.

from http://sangwonny.tistory.com/21 by ccl(A) rewrite - 2021-06-16 22:26:57