Angular2 컴포넌트, 디렉티브, 템플릿

이전 코드를 복제하기

Angular2 시작하기에서 Hello World 를 완료했습니다.

이전의 코드를 확장해서 구성요소, 모듈, 템플릿 작업을 해보도록 하겠습니다.

ng2-todolist 폴더를 만들고, 기존에 있던 코드들을 복사합니다.

 # cp -R ng2-helloworld ng2-todolist

package.json파일안에 "name"을 변경합니다.

"name": "ng2-todolist", 

index.html파일안에 title을 변경합니다.

<title>Angular 2 - My Todo List</title>

컴포넌트의 재사용

컴퐤넌트는 페이지에서 다른 요소를 만들고 정의하는 방법입니다. Angular 1에서는 디렉티브, 컨트롤러를 사용하여 컴포넌트 안에서 디렉티브을 찾도록 기능을 구현해야 했습니다.

app/app.component.ts파일을 수정해 보겠습니다.

import {Component} from 'angular2/core'

@Component({
  selector: 'my-component',
  template: '<div><button (click)="sayMyName()">Do Something Special</button></div>'
})
export class MyComponent {
    public name: String;
    constructor() {
        this.name = 'Angular 2 Rocks !';
    }
    sayMyName() {
        alert (this.name);
    }
}

class AppComponent 이름을 MyComponent 로 변경 하였기 때문에 index.html,main.ts 파일안의 내용을 변경해야 합니다.

<my-component>Loading...</my-component>

main.ts 파일 안에 다음으로 수정합니다.

import {bootstrap}    from 'angular2/platform/browser'
import {MyComponent} from './app.component'

bootstrap(MyComponent)

서버를 실행 시켜 봅니다. 버튼과 버튼을 눌렀을 경우에 경고창이 나오는 것을 확인할 수 있을것입니다.

 # npm start

Imgur

디렉티브 사용하기

app폴더에 highlight.directive.ts파일을 만들고 다음 내용을 추가 합니다.

import {Directive, ElementRef} from 'angular2/core';
@Directive({
    selector: '[myHighLight]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'orange';
    }
}

Directive : @directive 데코레이터를 위해 사용
ElementRef : DOM element 에 엑세스 할 수 있도록 허용합니다.

highlight.directive.ts파일을 다음과 같이 변경합니다.

import {Directive, ElementRef} from 'angular2/core';
@Directive({
    selector: '[myHighlight]',
     host: {
    '(mouseenter)': 'onMouseEnter()',
    '(mouseleave)': 'onMouseLeave()'
  }
})
export class HighlightDirective {
    private _el:HTMLElement;
    constructor(el: ElementRef) { this._el = el.nativeElement; }
    onMouseEnter() { this._highlight("yellow"); }
    onMouseLeave() { this._highlight(null); }
    private _highlight(color: string) {
        this._el.style.backgroundColor = color;
    }
}

host : MouseEnter, MouseLeave에서 CSS 변경을 수행하기 위해 호출할 두가지 메소드가 포함되어 있습니다.

템플릿의 위력

Angular는 템플릿을 사용해서 컴포넌트 안에서 클라이언트가 보는 것을 관리합니다. 템플릿에는 보여지기 위한 HTML 코드가 포함되어 있습니다. <script> 태그는 제외 한 대부분 모든 HTML 태그들을 템플릿에서 사용할 수 있습니다.
<html>,<body>,<base>와 같은 태그들을 사용할수는 있지만 실제로 템플릿에는 실제로 적용되지 않고 무시됩니다.
컴포넌트에 템플릿을 추가 하려면 템플릿 테그를 제거하고 templateUrl이라는 테그를 사용합니다.

templateUrl : 템플릿의 경로를 말합니다.

import {Component} from 'angular2/core'
import {HighlightDirective} from './highlight.directive';

@Component({
  selector: 'my-component',
  templateUrl: 'app/app.component.html',
  directives: [HighlightDirective]
})
export class MyComponent {
    public name: String;
    constructor() {
        this.name = 'Angular 2 Rocks !';
    }
    sayMyName() {
        alert (this.name);
    }
}

npm start를 사용하고 있다면 백그라운드에서 코드변경이 자동으로 브라우저에 적용되는 것을 확인할 수 있습니다.

간단히 날짜를 적용해 보겠습니다.
public today:Date 을 추가하고 new Date()를 추가해 봅니다.

app.component.ts부분을 아래와 같이 수정해 봅니다.

export class MyComponent {
    public name: String;
    public today: Date;

    constructor() {
        this.name = 'Angular 2 Rocks !';
        this.today = new Date();       
    }
    sayMyName() {
        alert (this.name);
    }
}

이제 app.component.html파일을 만들고 날짜가 표기 되도록 만들어 봅니다.

<h1>{{today | date:"fullDate"}}</h1>
| 표시
| 표시는 앵귤러1의 필터를 대체하는 파이프입니다. 필터처럼 템플릿 출력 형식을 지정하는데 도움이 됩니다.
반응형

+ Recent posts