我想使用HostBinding装饰器来添加一个不能像@HostBinding('class.myClass').
我知道有可能将它绑定到整个class属性,例如@HostBinding('class'),但这显然会重置所有直接添加到我使用它的主机元素的类。
那么是否可以使用HostBinding,但只添加一个类并在html中保留所有先前添加的类?
目前我最终得到了更丑陋的解决方案:
@Component({
...
})
class MyComponent implements OnInit {
constructor(private hostElement: ElementRef,
private renderer: Renderer2) { }
ngOnInit() {
const randomClass = `dynamic-${Math.floor(Math.random() * 10) + 1}`;
this.renderer.addClass(this.hostElement.nativeElement, dynamicClass);
}
}