要动态渲染ngClass,可以使用以下方法:
activeClass: string = 'active';
Dynamic Class
onClick() {
this.activeClass = 'inactive';
}
这样,当点击事件发生时,CSS类名会从'active'变为'inactive',从而实现动态渲染ngClass。
完整的示例代码如下:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
Dynamic Class
`,
styles: [`
.active {
color: blue;
font-weight: bold;
}
.inactive {
color: gray;
font-weight: normal;
}
`]
})
export class AppComponent {
activeClass: string = 'active';
onClick() {
this.activeClass = 'inactive';
}
}
这个示例中,初始状态下,div元素具有'active'类名,文字为蓝色和粗体。当点击按钮时,div元素的类名会切换为'inactive',文字颜色变为灰色和正常字体。