Using plain old javascript, this is so simple:
myElement.style.setProperty('property', 'value', 'important');
In Angular, not so much. I have done an exhaustive search absolutely everywhere and can not find one single example for how to do this, so i am asking the question here.
Either Renderer2 in Angular is broken or i am just doing this wrong.
i import the following into my component:
import {ElementRef, Renderer2, RendererStyleFlags2 } from '@angular/core';
and, in my constructor:
constructor(private elRef: ElementRef,
private renderer: Renderer2);
i set a style on an element in my template that works without issue:
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff');
when i try to set the important flag like this:
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff', RendererStyleFlags2.Important);
or like this:
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff', flags:RendererStyleFlags2.Important);
or like this:
public myFlags:RendererStyleFlags2;
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff', myFlags.Important);
or in another way like this:
public myFlags:RendererStyleFlags2.Important;
public myFlags:RendererStyleFlags2.Important = 1;
along with many other attempts using arrays and objects:
myFlags:any = {important: 1}
None of the above works.
This is the method as it exists in angular core:
setStyle(el: any, style: string, value: any, flags: RendererStyleFlags2): void {
if (flags & RendererStyleFlags2.DashCase) {
el.style.setProperty(
style, value, !!(flags & RendererStyleFlags2.Important) ? 'important' : '');
} else {
el.style[style] = value;
}
}
Can anyone tell me what i am doing wrong here?
It feels like you either need to use both of the renderer flags or add !important
to the string value instead.
const flags = RendererStyleFlags2.DashCase | RendererStyleFlags2.Important;
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff', flags);
Or
this.renderer.setStyle(this.elRef.nativeElement.querySelector('.my-div'), 'color', '#fff!important');
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