【发布时间】:2017-10-16 15:01:20
【问题描述】:
我想使用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);
}
}
【问题讨论】:
-
这个@HostBinding('class.my-class') myclass= true;将 my-class 添加到 :host 元素
-
是的,但正如我所说,我事先不知道我不想添加的类名。这就是我在示例中使用 Math.random 的原因。因此我不能使用硬编码
class.my-class -
即使我不了解如何在不知道类的情况下设置元素的样式,我也能明白这一点 - 顺便说一句,我认为你的方式就是要走的路
-
呵呵,是的,绝对有效。 :D 在现实世界的场景中,这个类实际上并不是完全动态的。有人正在为它编写样式,我们只是在给定的代码时间内不知道它。谢谢@Whisher
-
alligator.io/angular/using-renderer2 你也可以使用一个指令,你可以使用@Input 动态添加类
标签: angular angular2-hostbinding