Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove and add class in Angular renderer2 succinctly

Tags:

angular

Is it possible to add and remove a class from your element succinctly, in two line instead of writing a whole bunch of if else statement

Can you do this? (It is not working for me though.)

constructor(private renderer: Renderer2,private elRef: ElementRef) {
   const action = isDisabled ? 'addClass' : 'removedClass';
   this.renderer[action](div, 'disabled');
}

instead of

if (isDisabled) {
   this.renderer.addClass(div, 'disabled');
} else {
   this.renderer.removeClass(div, 'disabled');
}
like image 893
Arthur Decker Avatar asked Dec 07 '22 15:12

Arthur Decker


2 Answers

It is possible to do

const action = isDisabled ? 'addClass' : 'removeClass';
this.renderer[action](div, 'disabled');

Or even

this.renderer[isDisabled ? 'addClass' : 'removeClass'](div, 'disabled');

It is removeClass, not removedClass. And this is exactly the reason why this shouldn't be done.

Bracket notation disables type checking, so it becomes possible to access non-existing properties without triggering type errors.

Another reason is that the code may be harder to read.

like image 84
Estus Flask Avatar answered Feb 20 '23 21:02

Estus Flask


You can use the ngClass directive (https://angular.io/api/common/NgClass) to achieve this exact functionality:

<div [ngClass]="disabled ? 'disabled' : ''"></div>

If you need to use the renderer from inside the component class to achieve this, you could use:

this.renderer.setAttribute(div, 'class', this.disabled ? 'disabled' : '');

See this working Stackblitz with both approaches demonstrated: https://stackblitz.com/edit/angular-7ywg27

like image 38
vince Avatar answered Feb 20 '23 21:02

vince