Angular에서 CSS 클래스 일괄 적용

ngClass 지시자를 사용하면 태그에서 여러 CSS 클래스를 한 번에 켜고 끌 수 있습니다. 이 지시자는 객체를 값으로 받으며, 객체의 키는 클래스 이름이고, 값은 불리언 값입니다. 클래스는 값이 true로 설정된 경우 적용되고, false인 경우 적용되지 않습니다.

실제 예제를 살펴보겠습니다. 다음과 같은 클래스가 있다고 가정해 보겠습니다:

app/app.component.css.blue {
  color: blue;
}

.bold {
  font-weight: bold;
}

다음 예제들을 통해 블록에 대해 이러한 클래스를 켜고 끄는 방법을 살펴보겠습니다.

예제

한 클래스를 켜고 다른 클래스를 끄기:

app/app.component.html<div [ngClass]="{blue: true, bold: false}">
  text
</div>

예제

클래스의 상태가 컴포넌트 클래스의 속성에 저장되어 있다고 가정합니다:

app/app.component.tsexport class AppComponent {
  public isBlue: boolean = true;
  public isBold: boolean = false;
}

속성 값에 따라 클래스 적용을 바인딩합시다:

app/app.component.html<div [ngClass]="{blue: isBlue, bold: isBold}">
  text
</div>

예제

속성 안에 클래스와 그 상태를 담은 객체 전체가 있을 수 있습니다:

app/app.component.tsexport class AppComponent {
  public styles = {
    blue: false,
    bold: true,
  }
}

이 객체를 우리 블록에 바인딩합시다:

app/app.component.html<div [ngClass]="styles">
  text
</div>

예제

객체의 값을 컴포넌트 클래스의 다른 속성에서 얻을 수도 있습니다:

app/app.component.tsexport class AppComponent {
  public isBlue: boolean = false;
  public isBold: boolean = true;

  public styles = {
    blue: this.isBlue,
    bold: this.isBold,
  }
}

이 객체를 우리 블록에 바인딩합시다:

app/app.component.html<div [ngClass]="styles">
  text
</div>

실습 문제

Задание 1

두 개의 CSS 클래스를 생성하세요. 하나는 블록의 배경을 정의하고, 다른 하나는 글꼴 크기를 정의하도록 합니다.

Задание 2

두 개의 버튼을 만드세요. 첫 번째 버튼을 클릭하면 첫 번째 클래스가 토글되고, 두 번째 버튼을 클릭하면 두 번째 클래스가 토글되도록 합니다.