在Angular 2+中在运行时创建/更改CSS类的解决方法可以使用Renderer2
。以下是一个示例代码:
在组件的构造函数中注入Renderer2
:
import { Component, Renderer2 } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Dynamic Class Example
`,
styles: [`
.my-class {
color: red;
font-weight: bold;
}
`]
})
export class ExampleComponent {
applyClass: boolean = false;
constructor(private renderer: Renderer2) {}
toggleClass() {
this.applyClass = !this.applyClass;
const element = document.querySelector('.my-class');
if (this.applyClass) {
this.renderer.addClass(element, 'my-class');
} else {
this.renderer.removeClass(element, 'my-class');
}
}
}
在上述示例中,我们首先在组件类中创建了一个名为applyClass
的布尔值属性,它用于切换应用或取消应用CSS类。
在模板中,我们使用了[class.my-class]
绑定来根据applyClass
属性的值动态应用或移除CSS类。我们还在按钮的点击事件中调用了toggleClass()
方法。
在toggleClass()
方法中,我们使用document.querySelector('.my-class')
来获取具有.my-class
类的元素,并使用Renderer2
的addClass()
和removeClass()
方法来动态添加或移除该类。