nativeElement.classList.add() alternative

前端 未结 2 996
傲寒
傲寒 2021-01-02 01:33

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]\'

相关标签:
2条回答
  • 2021-01-02 02:17

    Thanks to Günter I've found the solution. This is his code but cleaned for anyone who can use it in the future.

    private color_: string;
    
    @Input()
    set color(value: string) {
        this.color_ = value;
    
        this.renderer.setElementClass(this.elementRef, 'md-' + this.color_, true);
    }
    
    get color(): string {
        return this.color_;
    }
    
    constructor(private elementRef: ElementRef, private renderer: Renderer) { }
    
    0 讨论(0)
  • @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){}
    } 
    
    0 讨论(0)
提交回复
热议问题