ngStyle

머맨·2021년 6월 8일
0

여러 개의 인라인 스타일을 추가 또는 제거한다. 이미 style 속성에 의해 이미 스타일이 지정되어 있을 때 ngStyle 디렉티브는 style 속성을 병합 한다.값은 객체로 작성. 단위가 필요한 경우 단위 추가가능

<div style="color: red; width: 100px;"
[ngStyle]="{ color: 'blue', 'height.px': 100 }">...</div>

result (병합)

<div style="color: blue; width: 100px; height: 100px;">...</div>
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div>
      Width: <input type="text" [(ngModel)]="width">
      <button (click)="increaseWidth()">+</button>
      <button (click)="decreaseWidth()">-</button>
    </div>
    <div>
      Height: <input type="text" [(ngModel)]="height">
      <button (click)="increaseHeight()">+</button>
      <button (click)="decreaseHeight()">-</button>
    </div>
    <button (click)="isShow=!isShow">{{ isShow ? 'Hide' : 'Show' }}</button>
    <!-- 스타일 지정  -->
    <div
      [ngStyle]="{
        'width.px': width,
        'height.px': height,
        'background-color': bgColor,
        'visibility': isShow ? 'visible' : 'hidden'
      }">
    </div>
  `
})
export class AppComponent {
  width = 200;
  height = 200;
  bgColor = '#4caf50';
  isShow = true;

  increaseWidth()  {
    this.width = +this.width + 10;
  }

  decreaseWidth()  {
    this.width = +this.width - 10;
  }

  increaseHeight() {
    this.height = +this.height + 10;
  }

  decreaseHeight() {
    this.height = +this.height - 10;
  }
}
profile
코맨코맨

0개의 댓글