Is it possible to add a dynamic class to host in Angular 2?

后端 未结 7 1957
眼角桃花
眼角桃花 2021-01-01 15:47

I know that in Angular2 I can add a class \'red\' to a component\'s selector element by doing this:

@Component({
    selector: \'selector-el\',
    host: {
          


        
7条回答
  •  时光说笑
    2021-01-01 15:55

    The Renderers setElementClass can be used to add or remove an arbitrary class. For example md-[color] where color is provided by an input

    
    
    @Component({
    // @Directive({
        selector: 'some-cmp',
        template: '...'
    })
    export class SomeComp {
        _color: string;
    
        @Input()
        set color(color: string) {
            this._color = color;
            this.renderer.setElementClass(this.elementRef.nativeElement, 'md-' + this._color, true);
        }
    
        get color(): string {
            return this._color;
        }
    
        constructor(private elementRef: ElementRef, private renderer: Renderer){}
    } 
    

    See also nativeElement.classList.add() alternative

提交回复
热议问题