angularangular2-hostbinding

How can I add an unknown class with HostBinding?


I want to use HostBinding decorator in order to add a class, which cannot be hardcoded like @HostBinding('class.myClass').

I know there is a possibility to bind it to the whole class attribute like @HostBinding('class'), but that will obviously reset all classes added directly to my host element in the place where it is used.

So is it possible to use HostBinding, but only to add one class and preserve all previously added classes in html?

Currently I ended up with uglier solution:

@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);
    }
}

Solution

  • Overriding the native class="" attribute with an @Input() class: string; looks promising. I haven't tested this very thoroughly, but it seems to work so far.

    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(' ');
        }
    
    }
    

    template with this:

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

    will output this:

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

    gist