Angular에서의 ngOnInit 훅

훅 ngOnInit은 컴포넌트가 초기화될 때 실행됩니다. 동작 방식은 클래스 생성자와 유사하지만, 서버에서 데이터를 로드하는 등 더 복잡한 작업을 수행할 수 있습니다.

이 훅을 사용하는 방법을 살펴보겠습니다. 먼저 해당 인터페이스를 임포트해야 합니다:

app/user/user.component.tsimport { OnInit } from '@angular/core';

다음으로, 컴포넌트 클래스에 인터페이스를 포함시켜야 합니다:

app/user/user.component.tsexport class UserComponent implements OnInit {

}

그 후, 컴포넌트 클래스 내에 ngOnInit 메서드를 작성할 수 있으며, 이 메서드는 클래스 초기화 시 자동으로 실행됩니다. 작동 방식을 확인해 보겠습니다:

app/user/user.component.tsexport class UserComponent implements OnInit {
  constructor() {
    console.log('constructor is started');
  }
  ngOnInit() {
    console.log('onInit is applied');
  }
}
Задание 1

프라이빗 메서드 show를 만들고 컴포넌트 초기화 시 호출하세요.