sharingStorage

Angular Directive 본문

Front-End/Angular

Angular Directive

Anstrengung 2022. 1. 27. 11:27

Angular Directive

Angular에는 DOM모양이나 동작을 지시하기 위한 명령인 Directive가 있다. HTML에 Angular가 간섭할 부분을 표시한다고 이해하면 쉽습니다.

앵귤러의 Directive에는 

 -Component Directive : 템플릿과 함께 사용하는 디렉티브 <app-root></app-root> 같이 selector가 app-root인 app.component를 표출해달라는 뜻

 -Attribute Directive : element나 component, 또다른 directive의 모양을 변경시키는 디렉티브

 -Structure Directive : DOM element를 더하거나 빼서 DOM을 변화시키는 디렉티브. ngIf, ngFor, ngSwitch등이 있다.

 -Costomer Directive : 사용자가 직접 생성한 Directive  생성 명령어 : ng g d 디렉토리이름

 

이번 게시글에서는 Attribute Directive를 중점으로 다루려고 한다.

 

Attribute Directive 

DOM에 스타일이나 동작을 부여한다.

Attribute 디렉토리에는 ngStyle, ngClass, ngModel등이 있다.

 

ngStyle

ngStyle은 HTML 스타일을 더하거나 제거한다.

ngStyle을 사용하려면 우선 module에 CommonModule을 import해야합니다.

CommonModule은 NgIf, NgClass, NgStyle, NgSwitch, DecimalPipe등 많은 angular의 기본 디렉티브를 사용할 수 있게 합니다. 

import { CommonModule } from '@angular/common';

html파일

HTML 파일에 style을 넣는 용도인 것 같은데 css파일이나 scss를 사용하면 될 것 같은데 추후에 용도를 알아봐야겠다.

 

 

ngModel

ngModel은 ts파일과 html파일 양쪽을 바인딩하는 양방향 바인딩에 필요한 디렉티브다.

ngModel을 사용하기 위해 module에 다음과 같이 FormsModule을 import해주어야 한다.

위 ngStyle 예제의 budget을 보면 이해가 갈 것이다.

 

 

ngClass

ngClass 디렉티브는 커스텀컨디션에 역동적으로 기반된 CSS class를 세팅하기 위해 사용된다.

타입에따라 CSS class를 업데이트할 수 있으며

 

String : 문자열로 리스트된 CSS class가 더해짐

Array : Array 요소로 선언된 CSS class가 더해짐

Object : key는 value값이 true일 때 추가되는 CSS class 

 

NgClass 디렉티브의 선택자는 [ngClass]이며 가장 기본적인 사례는 애플리케이션의 상태에 따라 클래스를 켜거나 끄는 것이다.

 

method - ngDoCheck()

ngDoCheck()는 기본 변화 감지기가 실행된 후 호출된 변화 감지를 수행하는 콜백 메서드

사용자 정의 변화 감지기능을 호출하는 생명주기 훅.

 

 

예시 (Angular와 npm, node는 설치되어있다고 가정)

1.  터미널에서 bootstrap을 설치해준다.

npm insatall bootstrap

1-2. angular.json 파일에서 

    "styles": [
              "src/styles.css",
              "./node_modules/bootstrap/dist/css/bootstrap.rtl.min.css" //이부분 추가
            ],

2. Singer.ts 파일을 작성

//Singer.ts
export class Singer{
    artist?: string;
    country?: string;
}

3. app.component.ts 파일 작성

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-login';

  singers:Singer[]=[
    {'artist': 'Michael Jackson',
      'country': 'USA'},
    {'artist':'Justine Bieber',
    'country': 'Canada'
  },
  {'artist': 'Daddy Yankee',
  'country': 'purto Rico'  
},
{
  'artist': 'A R Rehman',
  'country': 'India'
},
{
  'artist': 'Selena Gomez',
  'country': 'USA'
}
  ]

}

4. app.component.html파일 작성

<div class="container">
    <h4>NgClass</h4>
    <div *ngFor="let celeb of singers">
<p [ngClass]="{'text-success': celeb.country==='USA',
        'text-secondary': celeb.country==='Canada',
        'text-danger': celeb.country==='Puorto Rico',
        'text-info': celeb.country==='India'
}"> {{celeb.artist}} ({{celeb.country}})</p>

    </div>
</div>

5. angular 실행

ng serve

결과

 

브라우저에서 기본적으로 지원하는 이러한 유형의 상태 스타일의 경우 가능하면 css의사 클래스를 사용하는 것이 좋지만 선택된 리스트요쇼를 식별하는 style, 네비게이션 메뉴 안에 액티브 메뉴를 식별하는 style같은 경우는 ngClass의 사용이 좋다.

 

 

 

Reference

Comments