console.log("연록")

[Angular] Angular란?(Introduction 1) 본문

bone up/Angular

[Angular] Angular란?(Introduction 1)

연 록 2022. 3. 1. 19:32
728x90

앵귤러를 어떻게 공부하면 좋을까요?

 

라는 물음에 선임님은 앵귤러 공식 사이트를 추천해주셨다. 워낙 공식 사이트가 잘 되어있고, 또 한국어로 번역까지 되어있으므로 공식 사이트를 통한 학습이 다른 것들보단 낫다고 하셨다. 그러므로 나의 앵귤러 학습은 우선 공식 사이트를 바탕으로 진행된다.

https://angular.kr/guide/what-is-angular

 

Angular 가이드

Angular 가이드

angular.kr


Angular는 TypeScript를 기반으로 개발됨. 플랫폼이면서 동시에

  • 확장가능한 *컴포넌트 구조로 웹 애플리케이션을 만드는 프레임 워크
  • 라우팅, 폼 관리, 클라이언트-서버 통신 등 웹 개발에 필요한 라이브러리를 조화롭게 통합한 모음집
  • 애플리케이션 개발, 빌드, 테스트, 수정에 필요한 개발자 도구 제공

 

* 컴포넌트(Component)

 

애플리케이션을 구성하는 기본 단위 / 화면에서 특정 영역을 담당하며 동작을 처리하는 단위

 

컴포넌트는 세 가지로 구성

  • 컴포넌트 클래스는 데이터를 관리하고 동작을 처리
  • HTML 템플릿은 화면을 구성
  • 컴포넌트용 스타일은 화면이 어떤 모습으로 표시될 지 지정

 

@Component() 데코레이터가 붙는 TypeScript 클래스, HTML *템플릿, 스타일로 구성

@Component() 데코레이터의 역할

  • 컴포넌트가 템플릿에서 사용될 CSS 셀렉터 지정 -> 템플릿에서 이 셀렉터에 해당되는 HTML 엘리먼트마다 컴포넌트마다 인스턴스가 생성됨
  • Angular가 컴포넌트 내용으로 렌더링할 HTML 템플릿을 지정
  • 템플릿 HTML 엘리먼트의 모습을 지정해야하면 이 때 필요한 CSS 스타일 지정

기본 내용만 담은 Angular 컴포넌트

import { Component } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `
    <h2>Hello World</h2>
    <p>This is my first component!</p>
  `
})
export class HelloWorldComponent {
  // 여기에는 컴포넌트의 동작을 정의하는 코드가 들어갑니다.
}

▲ 이 컴포넌틑를 사용하려면 템플릿에 이 코드를 추가

<hello-world></hello-world>

Angular가 컴포넌트를 렌더링하고 난 후의 DOM

<hello-world>
    <h2>Hello World</h2>
    <p>This is my first component!</p>
</hello-world>

 

* 템플릿(Template)

 

HTML은 이 컴포넌트가 어떻게 렌더링 될 지 정의하기 위해 존재

템플릿은 인라인으로 정의 혹은 별도 파일로 작성 후 불러옴

 

Angular는 선언적인 템플릿 문법을 사용하기 때문에 화면에 표시되는 단위로 애플리케이션 로직을 깔끔하게 분리 가능

템플릿에는 표준 HTML 문법을 활용하기 때문에 구성하기 쉽고, 관리하기도 쉬우며, 나중에 수정하기도 쉬움

 

템플릿은 HTML 문법을 기본으로 작성

컴포넌트에 있는 값을 동적으로 반영하도로 구성 -> 컴포넌트의 상태가 변경되면 Angular가 자동으로 렌더링 된 DOM을 갱신

 

문자열을 동적으로 렌더링하는 컴포넌트의 템플릿 코드

<p>{{ message }}</p>

이 문자열은 컴포넌트 클래스에서 전달됨

import { Component } from '@angular/core';

@Component ({
  selector: 'hello-world-interpolation',
  templateUrl: './hello-world-interpolation.component.html'
})
export class HelloWorldInterpolationComponent {
    message = 'Hello, World!';
}

애플리케이션이 컴포넌트와 템플릿 로드 후 ▼

<p>Hello, World!</p>

 

문자열 바인딩(interpolation) : 템플릿 속 이중괄호 ({{ , }}) 문법을 통해

 

프로퍼티 바인딩 : 대괄호 사용([ , ]). HTML 엘리먼트의 프로퍼티(property), 어트리뷰트(attribute)에도 값을 할당

<p
  [id]="sayHelloId"
  [style.color]="fontColor">
  You can set my color in the component!
</p>

사용자의 동작 감지+이벤트 추가 : 소괄호 사용 (( , )). 키 입력, 마우스 이동, 클릭, 터치 등과 같은 동작 감지 후 이벤트 리스너 추가

<button
  [disabled]="canClick"
  (click)="sayMessage()">
  Trigger alert message
</button>

이벤트가 발생했을 때 실행 될 메서드를 컴포넌트 클래스에 구현한 코드 ▼

sayMessage() {
  alert(this.message);
}

 

 

Angular 템플릿(문자열 바인딩, 프로퍼티 바인딩, 이벤트 바인딩) 예시

 

typescript ▼

import { Component } from '@angular/core';

@Component ({
  selector: 'hello-world-bindings',
  templateUrl: './hello-world-bindings.component.html'
})
export class HelloWorldBindingsComponent {
  fontColor = 'blue';
  sayHelloId = 1;
  canClick = false;
  message = 'Hello, World';

  sayMessage() {
    alert(this.message);
  }

}

html

 

<button
  [disabled]="canClick"
  (click)="sayMessage()">
  Trigger alert message
</button>
<p
  [id]="sayHelloId"
  [style.color]="fontColor">
  You can set my color in the component!
</p>
<p>My color is {{ fontColor }}</p>

디렉티브(Directives)

 

템플릿에 추가 기능 구현 

Angular 디렉티브 중 많이 사용되는 디렉티브 : *ngIf*ngFor

디렉티브는 DOM 구조를 동적으로 변경할 수 있음 -> 다양한 용도로 활용 가능

 

*ngIf 사용 예시 

 

typescript 

import { Component } from '@angular/core';

@Component({
  selector: 'hello-world-ngif',
  templateUrl: './hello-world-ngif.component.html'
})
export class HelloWorldNgIfComponent {
  message = 'I\'m read only!';
  canEdit = false;

  onEditClick() {
    this.canEdit = !this.canEdit;
    if (this.canEdit) {
      this.message = 'You can edit me!';
    } else {
      this.message = 'I\'m read only!';
    }
  }
}

html 

<h2>Hello World: ngIf!</h2>

<button (click)="onEditClick()">Make text editable!</button>

<div *ngIf="canEdit; else noEdit">
    <p>You can edit the following paragraph.</p>
</div>

<ng-template #noEdit>
    <p>The following paragraph is read only. Try clicking the button!</p>
</ng-template>

<p [contentEditable]="canEdit">{{ message }}</p>

의존성 주입(Dependency Injection, DI)

 

Angular는 TypeScript 클래스를 활용하는 의존성 주입 시스템을 제공

-> 컴포넌트에 필요한 객체의 인스턴스를 어떻게 생성하는지 직접 신경쓸 필요 없음

인스턴스 생성은 Angular가 알아서 처리

-> 애플리케이션 코드를 좀 더 유연하게 작성, 테스트하기도 쉬움