如何使用HostBinding添加未知类?

时间:2017-10-16 15:01:20

标签: angular angular2-hostbinding

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

我知道有可能将它绑定到整个class属性,如@HostBinding('class'),但这显然会重置所有直接添加到我的主机元素的类。 / p>

那么可以使用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);
    }
}

1 个答案:

答案 0 :(得分:2)

使用class=""覆盖原生@Input() class: string;属性看起来很有希望。我还没有对此进行过彻底的测试,但到目前为止似乎有效。

import { Component, Input, HostBinding } from '@angular/core';

@Component({
    selector: 'gist-keeps-class',
    template: 'this component keeps class="class" attributes'
})
export class KeepsClass {

    @Input() booleanInput: boolean = false;
    @Input() stringInput: 'some-thing' | 'another-thing' | 'a-third-thing' = 'another-thing';

    @Input() class: string = ''; // override the standard class attr with a new one.
    @HostBinding('class')
    get hostClasses(): string {
        return [
            this.class, // include our new one 
            this.booleanInput ? 'has-boolean' : '',
            this.stringInput
        ].join(' ');
    }

}

模板:

<gist-keeps-class 
  class="some classes" 
  [booleanInput]="true" 
  [stringInput]="some-thing"
></gist-keeps-class>

将输出:

  <gist-keeps-class class="some classes has-boolean some-thing" >
    this component keeps class="class" attributes
  </gist-keeps-class>

gist