NativeElement.classList.add () alternative

I am trying to create a button component in angular 2. On the host, I have to set the dynamically generated css class name. (depending on the bound property)

'[ngClass]' on the host does not work.

I read that using elementRef.nativeElement.classList.add (value) element is also not the best way, because the List class is not supported on web pages (or so)

What are my best features for dynamically creating a class on a 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){} } 
+5
source share
2 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){} } 
+6
source

Thanks to Gunther, I found a solution. This is his code, but it is cleared 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) { } 
+3
source

Source: https://habr.com/ru/post/1243397/


All Articles