Angular 다양한 종류의 Template and Data Binding

Template And Data Binding in Angular를

Angular에서는 다양한 종류의 Binding을 제공한다. binding의 종류에 따라

  1. (element / component / directive) property
  2. (element / component / directive) event
  3. (rarely) an attribute name.

의 세가지 경우가 있다.

property binding

html 태그의 다양한 속성을 바인딩 해준다.

대상 Element property Component property Directive property

example1 예제에서 보여지듯이 다양한 종류의 속성을 바인딩 할 수 있다. 이미지를 불러오는 경로인 (src) 컴포넌트의 입력값을 주는 [hero] 바인딩, class 속성을 가르쳐주는 [ngClass] 등의 바인딩 사례가 있다.

<img [src]="heroImageUrl">
<app-hero-detail [hero]="currentHero"></app-hero-detail>
<div [ngClass]="{'special': isSpecial}"></div>

example2 [ngStyle]을 활용하여 동적으로 background-image 할당.

<div class="profile-image" [ngStyle]="{ 'background-image': 'url(' + image + ')'}">

Event Binding

html 태그에서 발생하는 다양한 종류의 event에 대한 binding이다.

대상 Element event Component event Directive event

example

<button (click)="onSave()">Save</button>
<app-hero-detail (deleteRequest)="deleteHero()"></app-hero-detail>
<div (myClick)="clicked=$event" clickable>click me</div>

(click)을 통해 클릭을 하는 시점에 함수를 발동하는 등의 역할을 수행한다.

(focus) and (focusout)

input 등의 경우 입력모드가 발동된 시점이나 특정 element가 focus 된 경우 동작을 나타낸다.

example

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

(ngModelChange)

해당 모델의 데이터 값이 바뀔 때마다 특정 함수를 실행할 수 있다.

Example {% raw %}

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" /> {{mymodel}}

{% endraw %}

참고자료

Two Way Binding을

이벤트와 속성등을 양방향으로 연결하는 바인딩이다.

대상 Event and property

example

<input [(ngModel)]="name">

Attribute Binding

대상 Attribute

example

<button [attr.aria-label]="help">help</button>

다음과 같이 value, selected를 바인딩 하는 데에도 사용 가능하다. 참조 {% raw %}

<select id="position">
  <option
    *ngFor="#contactType of contactTypes"
    [attr.value]="contactType.contactTypeId"
    [attr.selected]="contactType.contactTypeId == number ? true : null"
  >
    {{contactType.description}}
  </option>
</select>

{% endraw %}

class binding

특정 조건에서 class를 바인딩 해준다.

example

<div [class.special]="isSpecial">Special</div>

style binding

스타일 속성을 바인딩한다.

example

<button [style.color]="isSpecial ? 'red' : 'green'">

너비, 높이 등을 유동적으로 세팅하기 위해 다음과 같은 코드를 흔히 사용한다.

<div class="home-component"
 [style.width.px]="width"
 [style.height.px]="height">Some stuff in this div</div>

사이즈 조절을 위한 style binding

Structural Directive

HTML Layout에 영향을 주는 요소들이다. 대표적으로 ngIf ngFor 등이 있다.