컴포넌트(Component)는 Angular 애플리케이션을 구성하는 기본 단위이며, 거대한 웹 페이지의 일부분을 구성합니다. 컴포넌트는 특정 기능을 담당하도록 구분되어 있기 때문에, 컴포넌트를 모아서 만든 애플리케이션은 시간이 지나 규모가 커져도 관리하기 쉽습니다.
컴포넌트 정의하기
컴포넌트를 구성하는 요소들은 이렇습니다:
@Component데코레이터 - Angular가 인식할 수 있는 설정값을 지정합니다.- HTML 템플릿 - 렌더러가 DOM으로 렌더링하는 HTML입니다.
- CSS 셀렉터 - 컴포넌트를 HTML 문서에 사용하기 위해 지정하는 구분자입니다.
- TypeScript 클래스 - 사용자의 입력값을 처리하거나 서버로 요청을 보내는 등 컴포넌트의 동작을 정의합니다.
간단하게 만든 UserProfile 컴포넌트를 확인해 봅시다.
user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
})
export class UserProfile {
/* 컴포넌트 코드는 여기에 작성합니다. */
}
@Component 데코레이터에는 템플릿에 CSS 스타일을 지정하기 위해 styles 프로퍼티를 추가할 수 있습니다:
user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
styles: `
h1 {
font-size: 3em;
}
`,
})
export class UserProfile {
/* 컴포넌트 코드는 여기에 작성합니다. */
}
HTML과 CSS를 개별 파일로 분리하기
컴포넌트의 HTML과 CSS를 개별 파일로 정의하고 templateUrl과 styleUrl로 연결할 수도 있습니다:
user-profile.ts
@Component({
selector: 'user-profile',
templateUrl: 'user-profile.html',
styleUrl: 'user-profile.css',
})
export class UserProfile {
// 컴포넌트의 동작은 여기에 구현합니다.
}
user-profile.html
<h1>User profile</h1>
<p>This is the user profile page</p>
user-profile.css
h1 {
font-size: 3em;
}
컴포넌트 사용하기
Angular 애플리케이션은 여러 컴포넌트를 조합해서 만듭니다. 사용자 프로필 화면을 예로 들면, 이렇게 구현하는 식입니다:
여기에서 UserProfile 컴포넌트는 화면을 구성하기 위해 다른 컴포넌트들을 활용합니다.
컴포넌트를 불러와서 사용하려면:
- 컴포넌트 TypeScript 파일에
import구문을 추가하고 사용하려는 컴포넌트를 불러옵니다. @Component데코레이터에imports배열을 추가하고 사용하려는 컴포넌트를 이 배열에 추가합니다.- 컴포넌트 템플릿에 사용하려는 컴포넌트 셀렉터를 엘리먼트로 추가합니다.
그래서 UserProfile 컴포넌트 안에 ProfilePhoto 컴포넌트를 사용하려면 이렇게 구현하면 됩니다:
user-profile.ts
import {Component} from '@angular/core';
import {ProfilePhoto} from './profile-photo';
@Component({
selector: 'user-profile',
imports: [ProfilePhoto],
template: `
<h1>User profile</h1>
<profile-photo />
<p>This is the user profile page</p>
`,
})
export class UserProfile {
// 컴포넌트의 동작은 여기에 구현합니다.
}
팁: Angular 컴포넌트를 자세하게 알아보고 싶은가요? 그러면 컴포넌트 심화 가이드 문서를 참고하세요.
다음 단계
Angular에서 컴포넌트가 어떤 역할을 하는지 알아봤습니다. 이제 동적 데이터를 다루는 방법을 알아봅시다.