Angular 기초 (Angular Basics)
Angular는 강력한 풀스택 프론트엔드 프레임워크다. 타입스크립트와 컴포넌트 기반 구조로 대규모 애플리케이션에 적합하다. 이번에는 Angular의 기본부터 심화까지 코드와 함께 자세히 풀어보려고 한다.
Angular를 잘 이해하면 구조화된 웹 앱을 효율적으로 만들 수 있다. 하나씩 단계별로 알아보자.
Angular 시작하기
Angular를 사용하려면 먼저 Angular CLI로 프로젝트를 생성한다:
# Angular CLI 설치
npm install -g @angular/cli
# 새 프로젝트 생성
ng new my-app
cd my-app
ng serve
// src/app/app.component.html
<h1>안녕, Angular!h1>
ng serve
로 앱을 실행하면 기본 템플릿이 표시된다.
1. 컴포넌트 생성
Angular는 컴포넌트로 UI를 구성한다. 새 컴포넌트를 만들어보자:
# 컴포넌트 생성
ng generate component greeting
// src/app/greeting/greeting.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `안녕, {{ name }}!
`
})
export class GreetingComponent {
name = '홍길동';
}
// src/app/app.component.html
<app-greeting>app-greeting>
@Component
데코레이터로 컴포넌트를 정의하고 사용했다.
2. 데이터 바인딩
Angular는 다양한 데이터 바인딩을 제공한다:
// src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
입력값: {{ text }}
`
})
export class AppComponent {
text = '';
}
// src/app/app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [FormsModule]
})
[(ngModel)]
로 양방향 바인딩을 구현했다.
3. 디렉티브 활용
Angular의 디렉티브로 동적인 UI를 만든다:
// src/app/app.component.ts
@Component({
template: `
보이는 상태
`
})
export class AppComponent {
isVisible = false;
toggle() {
this.isVisible = !this.isVisible;
}
}
*ngIf
로 조건을, (click)
으로 이벤트를 처리했다.
4. 리스트 렌더링
*ngFor
로 리스트를 렌더링한다:
// src/app/app.component.ts
@Component({
template: `
- {{ item }}
`
})
export class AppComponent {
items = ['사과', '바나나', '오렌지'];
}
*ngFor
로 배열을 순회하며 표시했다.
5. 서비스와 의존성 주입
서비스로 데이터를 관리한다:
# 서비스 생성
ng generate service data
// src/app/data.service.ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class DataService {
getItems() {
return ['사과', '바나나'];
}
}
// src/app/app.component.ts
import { DataService } from './data.service';
@Component({
template: `- {{ item }}
`
})
export class AppComponent {
items: string[];
constructor(private dataService: DataService) {
this.items = dataService.getItems();
}
}
의존성 주입으로 서비스를 컴포넌트에 연결했다.
6. HTTP 요청
API 데이터를 가져와보자:
// src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule]
})
// src/app/app.component.ts
import { HttpClient } from '@angular/common/http';
@Component({
template: `- {{ post.title }}
`
})
export class AppComponent {
posts: any[] = [];
constructor(private http: HttpClient) {
this.http.get('https://jsonplaceholder.typicode.com/posts')
.subscribe(data => this.posts = (data as any).slice(0, 5));
}
}
HttpClient
로 데이터를 가져와 렌더링했다.
7. 성능과 구조에 미치는 영향
Angular가 앱에 어떤 영향을 주는지 보자:
- 성능: 변경 감지로 효율적이지만, 초기 로드가 약간 무거울 수 있다.
- 구조: 타입스크립트와 모듈로 대규모 앱에 강하다.
컴포넌트와 서비스가 Angular의 강력함을 보여준다.
마무리
Angular는 컴포넌트, 바인딩, 서비스를 통해 구조화된 웹 개발을 가능하게 한다. 기본부터 HTTP 요청까지 다채롭게 활용할 수 있다.
'코딩 공부 > 자바스크립트' 카테고리의 다른 글
78. 자바스크립트 Jest 사용법 (Using Jest) (0) | 2025.03.26 |
---|---|
77. 자바스크립트 유닛 테스트 기초 (Unit Testing Basics) (2) | 2025.03.26 |
75. Vue.js 기초 (Vue.js Basics) (0) | 2025.03.25 |
74. Node.js 기초 (Node.js Basics) (2) | 2025.03.25 |
73. React 기초 (React Basics) (0) | 2025.03.24 |