2

我想使用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);
    }
}
4

1 回答 1

4

用一个看起来很有希望的覆盖原生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>

要旨

于 2018-05-19T18:24:48.627 回答