Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Either i am using Angular Renerer2 wrong, or it is broken. Can anyone figure this out?

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?

like image 250
DevMike Avatar asked Apr 13 '18 18:04

DevMike


1 Answers

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');
like image 137
Daniel W Strimpel Avatar answered Nov 01 '22 07:11

Daniel W Strimpel