Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nativeElement.classList.add() alternative

I'm trying to create a button component in angular 2. At the host I have to set a dynamically generated css classname. (depending on binded property)

'[ngClass]' on host does not work.

I've read that using elementRef.nativeElement.classList.add(value) is not the best way either, because classList is not supported on webworkers (or so)

What are my best options to generate the class dynamically on host?

@Component({
    selector: '[md-button]',
})
export class MdButton {
    color_: string;

    @Input
    set color() {
        this.color_ = value;
        if (this.elementRef !== undefined) {
            this.elementRef.nativeElement.classList.add('md-' + this.color_);
        }   
    }

    get color(): string {
        return this.color_;
    }

    constructor(public elementRef: ElementRef){}
} 
like image 743
BakGat Avatar asked Feb 19 '16 13:02

BakGat


1 Answers

@Component({
    selector: '[md-button]' //,
    // host: { '[class]': 'classList()' }
})
export class MdButton {
    color_: string;

    // classList() {
    //  return 'md-' + this.color_;
    // }

    @Input
    set color() {
        this.color_ = value;
        // if (this.elementRef !== undefined) {
        //    this.elementRef.nativeElement.classList.add('md-' + this.color_);
        // }   

        this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true);
    }

    get color(): string {
        return this.color_;
    }

    constructor(public elementRef: ElementRef, private renderer: Renderer2){}
} 
like image 189
Günter Zöchbauer Avatar answered Oct 21 '22 17:10

Günter Zöchbauer