Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何添加具有HostBinding的未知类?_Angular_Angular2 Hostbinding - Fatal编程技术网

Angular 如何添加具有HostBinding的未知类?

Angular 如何添加具有HostBinding的未知类?,angular,angular2-hostbinding,Angular,Angular2 Hostbinding,我想使用HostBindingdecorator来添加一个类,它不能像@HostBinding('class.myClass')那样硬编码 我知道有可能将它绑定到整个类属性,比如@HostBinding('class'),但这显然会重置直接添加到宿主元素中的所有类 那么,是否可以使用HostBinding,但只添加一个类并将以前添加的所有类保留在html中 目前,我最终得到了更丑陋的解决方案: @Component({ ... }) class MyComponent implement

我想使用
HostBinding
decorator来添加一个类,它不能像
@HostBinding('class.myClass')那样硬编码

我知道有可能将它绑定到整个
属性,比如
@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);
    }
}

使用
@Input()class:string重写本机
class=”“
属性看起来很有希望。我还没有完全测试过这个,但到目前为止它似乎很有效

从'@angular/core'导入{Component,Input,HostBinding};
@组成部分({
选择器:'gist保持类',
模板:'此组件保留class=“class”属性'
})
导出类KeepsClass{
@Input()booleanInput:boolean=false;
@Input()stringInput:'某件事'|'另一件事'|'第三件事'='另一件事';
@Input()类:string='';//用新类重写标准类attr。
@主机绑定('类')
获取主机类():字符串{
返回[
this.class,//包括我们的新
this.booleanInput“”具有布尔值“”:“”,
这是stringInput
].加入(“”);
}
}
具有以下内容的模板:


将输出以下内容:


此组件保留class=“class”属性

this@HostBinding('class.my class')myclass=true;将我的类添加到:host element是的,但是正如我所说的,我事先不知道我不想添加的类名。这就是我在示例中使用Math.random的原因。因此,我不能使用硬编码的
类。我的类
我可以看到这一点,即使我不知道如何在不知道类的情况下设置元素的样式-顺便说一句,我认为你的方式是通往goHehe的方式,是绝对有效的点:在真实场景中,这个类实际上并不是完全动态的。有人正在为它编写一个样式,我们只是在给定的时间内不知道它的代码。谢谢@Whisher,您还可以使用一个指令,使用@Inputperfect answer动态添加类