앵귤러/03 템플릿&데이터 바인딩

03 라이프사이클 후크(Lifecycle hooks) 08

linor 2017. 8. 20. 11:56

AfterContent

AfterContent 샘플은 Angular가 외부 콘텐츠를 컴포넌트로 투영 한 후 Angular가 호출한 AfterContentInit() AfterContentChecked() 후크를 탐색합니다.

 

콘텐츠 투영

컨텐츠 투영은 컴포넌트 외부에서 HTML 컨텐츠를 가져 와서 해당 컨텐츠를 지정된 위치의 컴포넌트 템플릿에 삽입하는 방법입니다.

이전 AfterView 예제에서 이 변형을 고려하십시오. 이번에는 템플릿 내에 자식 뷰를 포함하는 대신 AfterContentComponent의 부모로 부터 컨텐트를 가져옵니다. 부모 템플릿은 다음과 같습니다.

AfterContentParentComponent (template excerpt)

`<after-content>

   <my-child></my-child>

 </after-content>`

<my-child> 태그는 <after-content> 태그 사이에 위치합니다. 내용을 컴포넌트에 투영하지 않으려면 컴포넌트의 엘리먼트 태그 사이에 내용을 넣지 마십시오.

이제 컴포넌트의 템플릿을 살펴보십시오.

AfterContentComponent (template)

template: `

  <div>-- projected content begins --</div>

    <ng-content></ng-content>

  <div>-- projected content ends --</div>`

<ng-content> 태그는 외부 콘텐츠를 위한 공간입니다. 이것은 Angular에게 해당 내용을 삽입 할 위치를 알려줍니다. 이 경우, 투영 된 내용은 부모로에 있는 <my-child>입니다.


콘텐츠 투영의 기록 표시는 두 가지입니다.

l  컴포넌트 엘리먼트 태그 사이의 HTML.

l  컴포넌트 템플릿에 <ng-content>의 위치

 

AfterContent 후크

AfterContent 후크는 AfterView 후크와 비슷합니다. 주요 차이점은 하위 컴포넌트에 있습니다.

l  AfterView 훅은, 엘리먼트 템플릿이 컴퍼넌트의 템플릿 내에 표시되는 자식 컴퍼넌트 인 ViewChildren에 관련됩니다.

l  AfterContent 후크는 Angular가 컴포넌트에 투영하는 하위 컴포넌트인 ContentChildren에 관련됩니다.

다음 AfterContent 후크는 콘텐츠 하위의 값 변경을 기반으로 작업을 수행하며 @ContentChild로 장식 된 프로퍼티를 통해 해당 하위 콘텐츠를 조회해야만 접근 할 수 있습니다.

AfterContentComponent (class excerpts)

export class AfterContentComponent implements AfterContentChecked, AfterContentInit {

  private prevHero = '';

  comment = '';

 

  // Query for a CONTENT child of type `ChildComponent`

  @ContentChild(ChildComponent) contentChild: ChildComponent;

 

  ngAfterContentInit() {

    // contentChild is set after the content has been initialized

    this.logIt('AfterContentInit');

    this.doSomething();

  }

 

  ngAfterContentChecked() {

    // contentChild is updated after the content has been checked

    if (this.prevHero === this.contentChild.hero) {

      this.logIt('AfterContentChecked (no change)');

    } else {

      this.prevHero = this.contentChild.hero;

      this.logIt('AfterContentChecked');

      this.doSomething();

    }

  }

  // ...

}

 

AfterContent에서 단방향 흐름 걱정 없음

이 컴포넌트의 doSomething() 메서드는 컴포넌트의의 데이터 바인딩된 comment 프로퍼티를 즉시 업데이트합니다.

Angular AfterView 후크 중 하나를 호출하기 전에 두 AfterContent 후크 모두를 호출한다는 것을 상기하십시오. Angular는 이 컴포넌트 뷰의 컴포지션을 완료하기 전에 투영 된 내용의 구성을 완료합니다. AfterContent... AfterView... 후크 사이에 작은 창이 있어 호스트보기를 수정합니다.