TypeScript 를 기반으로 하는 개발 플랫폼 - Angular

1. 컴포넌트(Component)

구성요소 3가지

1.@Component() 데코레이터가 붙는 TypeScript 클래스
2.HTML 템플릿
3.스타일
3.1 - 컴포넌트를 템플릿에 추가할 때 사용하는 CSS 셀렉터
3.2 - 추가로 컴포넌트가 표시되는 모습을 정의하는 CSS 스타일

데코레이터는 Angular에 필요한 정보를 지정하는 역할

  1. 템플릿에 사용될 CSS 셀렉터를 지정
  2. 컴포넌트 내용으로 렌더링할 HTML템플릿을 지정

기본 내용 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가 컴포넌트를 렌더링하고 난다면

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

DOM은 이렇게 된다.

컴포넌트의 구조

@Component({
  selector: 'app-component-overview',
  templateUrl: './component-overview.component.html',
  styleUrls: ['./component-overview.component.css']
})

컴포넌트 클래스를 정의하는 class구문

export class ComponentOverviewComponent {

}

2. 템플릿(Templates)

  • 템플릿은 인라인으로 정의 or 별도 파일로 작성해서 불러올수 있다

템플릿은 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!';
}

위 코드에 있는 message에서 따오는 것이다.

즉 , 애플리케이션에서 컴포넌트와 템플릿을 로드하고 나면

<p>Hello, World!</p>

위와 같은 화면을 볼 수 있다.

{{,}}

템플릿에 이중 중괄호 문법

-> 문자열을 바인딩하는 문법이다.

HTML엘리먼트의 프로퍼티 or 어트리뷰트에 값을 할당하는 프로퍼티 바인딩 문법도 제공

[]

-위 문법은 컴포넌트 클래스에 있는 값을 프로퍼티나 어트리뷰트로 바인딩하는 문법

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

()

-키입력, 마우스 이동, 클릭, 터치등과 같은 사용자의 동작을 감지하고 이 동작에 반응하기 위해 이벤트 리스터를 추가할 수 있다.

이때 감지하려는 이벤트 이름을 소괄호 ((,))로 감싸면 된다.

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

위 이벤트가 발생했을때 실행될 메서드를 구현하려면

컴포넌트 클래스에 아래와 같이 기입하면 된다.

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

디렉티브

  • 템플릿에 추가 기능을 구현하기 위해 사용

  • Angular 디렉티브 중에서 가장 많이 사용되는 디렉티브에는

ngIf 와 ngFor 가 있다.

  • DOM구조를 동적으로 변경할 수 있다. -> 다양한 용도로 활용

.ts

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 type="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>

3. 의존성 주입(Dependency injection,DI)

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

즉 , 컴포넌트에 필요한 객체와 인스턴스를 어떻게 생성하는지 직접
신경쓸 필요가 없다.

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

  1. logger.service.ts

Logger클래스가 정의

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

@Injectable({providedIn: 'root'})
export class Logger {
  writeCount(count: number) {
    console.warn(count);
  }
}
  1. hello-world-di.component.ts

Angular컴포넌트가 정의

import { Component } from '@angular/core';
import { Logger } from '../logger.service';

@Component({
  selector: 'hello-world-di',
  templateUrl: './hello-world-di.component.html'
})
export class HelloWorldDependencyInjectionComponent  {
  count = 0;

  constructor(private logger: Logger) { }

  onLogMe() {
    this.logger.writeCount(this.count);
    this.count++;
  }
}

private logger: Logger

위 코드를 추가함으로써 Logger 서비스가 의존성 객체로 주입되도록 요청 할 수 이싸.

profile
밑거름이라고생각합니다

0개의 댓글

Powered by GraphCDN, the GraphQL CDN