CSS 클래스를 추가하거나 제거한다.
<!-- app.component.html -->
<div [ngClass]="isSpecial ? 'specail-class' : null">This is a Special</div>
//app.component.ts
export class AppComponent{
isSpecial : true
}
//app.component.css
.sepecail-class{
color : red,
font-weight : bold
}
HTML 스타일을 추가하거나 제거한다.
<!-- app.component.html -->
<div [ngStyle]="currentStyles">
내용이 여기에 있습니다.
</div>
<button (click)="setCurrentStyles()">스타일 변경</button>
//app.component.ts
export class AppComponent {
title = 'angularLearn';
currentStyles : Record<string, string> = {};
setCurrentStyles() {
const canSave = true; // 실제 속성 값으로 대체하세요
const isUnchanged = false; // 실제 속성 값으로 대체하세요
const isSpecial = true; // 실제 속성 값으로 대체하세요
this.currentStyles = {
'font-style': canSave ? 'italic' : 'normal',
'font-weight': !isUnchanged ? 'bold' : 'normal',
'font-size': isSpecial ? '24px' : '12px'
};
}
TypeScript - Record<string, string>
currentStyles: Record<string, string> = {};
1. Record : TypeScript에서 제공하는 유틸리티 타입 중 하나이다. 이는 문자열 키를 가진 딕셔너리나 객체를 나타내는데 사용된다. 이 경우 키는string
타입이다.
2.<string, string>
: 이것은Record
타입의 제네릭 매개변수이다.Record<string, string>
의 맥락에서, 이는 키가string
타입인 것을 의미한다.
양방향 데이터 바인딩은 데이터의 변경이 모델과 뷰 간에 양쪽으로 이루어지는 프로그래밍 패턴이다. 이는 사용자가 UI 요소를 통해 값을 입력하면 모델이 업데이트되고, 반대로 모델의 값이 변경되면 이를 UI에 반영하는 것을 의미한다.
Angular에서는 [(ngModel)]
을 사용하여 양방향 데이터 바인딩을 구현한다.
다른 언어나 프레임워크에서도 이와 유사한 패턴이 존재한다.
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>
*ngFor 표현식을 이렇게 작성하면 호스트 엘리먼트 근처에 이 추가되면서 배열에 있는 item 항목마다 반복되면서 item 프로퍼티가 바인딩된다.
배열 항목이 변경되는 것을 추적하면 불필요한 함수 실행 횟수를 줄일 수 있다. 프로퍼티를 사용하면 Angular는 배열에서 변경된 항목만 화면에서 갱신하고 렌더링을 새로한다.
trackByItems(index: number, item: Item): number { return item.id; }
<div *ngFor="let item of items; trackBy: trackByItems">
({{item.id}}) {{item.name}}
</div>