반응형

Directive는 DOM 요소의 모양이나 동작을 변경합니다.

앵귤라에는 세가지 종류의 디렉티브가 있다.


  • Components  -  템플릿이 있는 디렉티브
  • 구조적 디렉티브 - DOM요소들을 추가, 제거 하여 DOM 레이아웃을 변경합니다.
  • 속성 디렉티브 - 요소, 구성 요소 또는 다른 디렉티브의 모양 또는 동작을 변경합니다.

콤포넌트 디렉티브는 가장일반적인 방법 이다.
구조적 디렉티브는 뷰의 구조를 변경할때 쓰인다.
속성 디렉티브는 요소의 속성으로 사용됩니다.


<p appHighlight>Highlight me!</p>


CLI명령을 사용해여 디렉티브 생성

ng generate directive highlight


디렉티브 정의는 앵귤라의 모듈 정의와 같게 정의 하면 된다.


hightlight.directive.ts

import { Directive } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor() { } }


Directive를 import하고 @Directive 데코레이터를 사용해서 정의한다.

디렉티브의 설정에 selector은 CSS 속성 선택자를 사용한다.


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

디렉티브의 생성자에 ElementRef 주입 하고, 네이티브요소 속성을 통해 DOM 요소에 직접 액세스 할수 있다.


@angular/core 에 HostListener를 import 해서 이벤트 응답을 추가할수 있다.


import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { } @HostListener('mouseenter') onMouseEnter() { this.highlight('yellow'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; }


@Input 데이터 바인딩을 이용하여 값을 디렉티브에 전달한다.


import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { } @Input('appHighlight') highlightColor: string; //input 데이터 별칭을 사용한경우

//@Input highlightColor: string; //input 데이터 별칭을 사용 안한경우. @HostListener('mouseenter') onMouseEnter() { this.highlight(this.highlightColor || 'red'); } @HostListener('mouseleave') onMouseLeave() { this.highlight(null); } private highlight(color: string) { this.el.nativeElement.style.backgroundColor = color; } }


<p [appHighlight]="color">Highlight me!</p>


반응형

+ Recent posts