Angular 中的 ngClass 是什么?
chatgpt 回答:
在Angular中,ngClass 是一个内置的指令,用于动态地添加或移除 HTML 元素的 CSS 类。它允许你根据条件设置一个或多个 CSS 类,可以是对象、数组或字符串。
使用方式:
- 字符串语法
<div [ngClass]="'class1 class2'">...</div>
在这个例子中,class1 和 class2 类将被添加到 div 元素中。
- 数组语法
<div [ngClass]="['class1', 'class2']">...</div>
使用数组语法可以添加多个类到元素中。
- 对象语法
<div [ngClass]="{'class1': condition1, 'class2': condition2}">...</div>
基于条件动态地添加或移除类。如果 condition1 为 true,class1 类将被添加到元素中;如果 condition2 为 true,class2 类将被添加到元素中。
- 使用方法调用
<div [ngClass]="getClassNames()">...</div>
getClassNames() 是一个在组件中定义的方法,用于返回需要应用的类名。
ngClass 是一个非常有用的指令,能够根据组件中的变量或条件动态地管理元素的样式类,让你可以根据特定的情况或状态来改变元素的外观和行为。
Youtube tutorial:
app.component.ts:
// 类型检查
interface Pokemon {id: number;name: string;type: string;isCool: boolean;
}@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'],
})
export class AppComponent {pokemons: Pokemon[] = [{id: 1,name: 'pikachu',type: 'electric',isCool: false,},{id: 2,name: 'squirtle',type: 'water',isCool: true,},{id: 3,name: 'charmander',type: 'fire',isCool: true,},];constructor() {}
}
app.component.html,但是没有使用 ngClass 设置 CSS,而是使用属性绑定语法,动态添加 cool-bool CSS 类到 td 元素中。
<table><thead><th>Index</th><th>Name</th><th>Type</th></thead><tbody><tr *ngFor="let pokemon of pokemons; let i = index"><td [class.cool-bool]="pokemon.isCool">{{ i }}</td><td>{{ pokemon.name }}</td><td>{{ pokemon.type }}</td></tr></tbody>
</table>
app.component.css
.cool-bool {/* 蓝色 */background: #0094ff;
}
可以看到如下的界面:

使用 ngClass 对象语法:
app.component.html:
<table><thead><th>Index</th><th>Name</th><th>Type</th></thead><tbody><tr *ngFor="let pokemon of pokemons; let i = index"><td [class.cool-bool]="pokemon.isCool">{{ i }}</td><td>{{ pokemon.name }}</td><td>{{ pokemon.type }}</td></tr><tr *ngFor="let pokemon of pokemons; let i = index"><td [ngClass]="{'cool-bool':pokemon.isCool}">{{ i }}</td><td>{{ pokemon.name }}</td><td>{{ pokemon.type }}</td></tr></tbody>
</table>
Web 页面:
