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');
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With