본문 바로가기
Frontend/Angular

[Angular] 01. Component

by jyc_ 2025. 1. 31.
 Angular 공식 문서를 실습하고 정리하는 글입니다.

 

Component (컴포넌트)

  • 컴포넌트는 Angular 앱의 주요 구성 요소이다.
  • 각 컴포넌트는 더 큰 범위의 웹페이지의 일부를 나타낸다.
  • 애플리케이션을 컴포넌트 단위로 분리하면 유지보수가 용이해진다.

 

컴포넌트 구성 요소

// 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 {
  username: string = 'John';
  email: string = 'john.doe@example.com';

  constructor() {
    // 초기화 로직
  }

  updateProfile(newUsername: string) {
    this.username = newUsername;
  }
}
  1. @Component 데코레이터: 컴포넌트의 메타 데이터 정의
  2. HTML template: 컴포넌트의 뷰 정의(화면에 표시될 내용 결정)
  3. CSS selector: 컴포넌트를 HTML에서 사용할 때의 태그 이름 정의
  4. TypeScript 클래스: 컴포넌트의 로직과 동작 정의

 

이 컴포넌트는 <user-profile></user-profile> 형식으로 사용할 수 있다.

// user-profile.ts
@Component({
  selector: 'user-profile',
  templateUrl: 'user-profile.html',
  styleUrl: 'user-profile.css',
})
export class UserProfile {
  // Component behavior is defined in here
}

<!-- user-profile.html -->
<h1>Use profile</h1>
<p>This is the user profile page</p>

/* user-profile.css */
h1 {
  font-size: 3em;
}

HTML과 CSS파일을 외부에서 가져와 사용할 수도 있다.

 

컴포넌트 사용

여러 컴포넌트를 결합하여 애플리케이션을 빌드한다.

UserProfile 컴포넌트 구성

  1. TS 파일에서, 사용하려는 컴포넌트를 import한다.
  2. @Component 데코레이터에서, 사용하고 싶은 컴포넌트를 imports 배열에 추가한다.
  3. 템플릿에서 사용하려는 컴포넌트의 선택자를 사용하여 컴포넌트에 추가한다.

 

UserProfile에서 ProfilePhoto 컴포넌트 사용하기

// user-profile.ts
import {ProfilePhoto} from 'profile-photo.ts';

@Component({
  selector: 'user-profile',
  imports: [ProfilePhoto],
  template: `
    <h1>User profile</h1>
    <profile-photo />
    <p>This is the user profile page</p>
  `,
})
export class UserProfile {
  // Component behavior is defined in here
}

 

실습

1. 컴포넌트를 통해 문장 출력

say-hello.component.ts 파일 생성
파일 import, imports 배열에 추가
결과

 

 

2. 컴포넌트를 결합하여 이미지 출력

이미지 경로 설정에 주의해야 한다!!

print-img.components.ts 파일 생성
say-hello.components.ts 수정

 

결과

'Frontend > Angular' 카테고리의 다른 글

[Angular] 05. Components: Selectors  (1) 2025.01.31
[Angular] 04. Dependency Injection  (0) 2025.01.31
[Angular] 03. Dynamic interface with templates  (0) 2025.01.31
[Angular] 02. Signal  (0) 2025.01.31
[Angular] 00. 사전 준비, Angular 설치  (0) 2025.01.28