본문 바로가기
패스트캠퍼스/수업내용정리

2019-06-24 Angular 디렉티브

by sunnykim91 2019. 6. 24.

Angular 디렉티브

 

디렉티브는 애플리케이션 전역에서 사용할 수 있는 공통 관심사를 컴포넌트에서 분리하여 구현한 것으로 컴포넌트의 복잡도를 낮추고 가독성을 향상시킨다. 컴포넌트도 뷰를 생성하고 이벤트를 처리하는 등 DOM을 관리하기 때문에 큰 의미에서 디렉티브로 볼 수 있다.

 

// test directive
import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[appTextBlue]'
})
export class TextBlueDirective {

  constructor(public el: ElementRef) {   // 의존성 주입 , public을 사용한 el은 TextBlueDirective클래스안 클래스필드 어디서든 사용가능
    console.log('TextBlueDirective', el);
    this.el.nativeElement.style.color = "blue"; 
  }
}

 

// test.component
import { Component } from '@angular/core';

@Component({
  selector: 'app-test-directive',
  template: `
    <p appTextBlue>Hello</p>  <!--여기서 p요소는 호스트요소이다. = 디렉티브안에 el -->
  `,
  styles: []
})
export class TestDirectiveComponent   {

   
}
반응형