Angular : how to programatically set css style to body as important in typescript

Viewed 3601

Under my angular app

I'm using this code to set a custom body style :

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
    this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden';
  }

for some specific scneario i myust add "important" to it

this would be like this :

   this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden !important';

But that is not working , and "important is not added to the style.

To note ; since i need to apply this for the body itself , and not to a specific html element unside my component , ngStyle cannot do it.

Suggestions ??

4 Answers

This should work.

this.elementRef.nativeElement.ownerDocument.body.style.setProperty("overflow-y", "hidden", "important");

html:

<h2 #elem>hiper king</h2>

ts:

import { Component, ViewChild, Renderer2, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements AfterViewInit {
  title = 'stackApp';
  @ViewChild('elem') elem: ElementRef;
  constructor(private renderer: Renderer2) { }
  ngAfterViewInit() {
    this.renderer.setAttribute(this.elem.nativeElement, 'style', 'overflowY: hidden !important');
  }
}

Try this

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

When you need to add a class to the body, Renderer2 is a good option. First create 2 classes:

.overflowYHidden {
  overflow-y: hidden;
}
.overflowYHiddenImportant {
  overflow-y: hidden !important;
}

Now use the renderer:

import { Renderer2, RendererFactory2 } from '@angular/core';

// class declaration skipped

_renderer: Renderer2;

constructor(rendererFactory: RendererFactory2) {
  this._renderer = rendererFactory.createRenderer('body', null);
}

I don't know what logic you're using for when to use important:

if (someCondition) {
  this._renderer.addClass(document.body, 'overflowYHidden');
  this._renderer.removeClass(document.body, 'overflowYHiddenImportant');
} else {
  this._renderer.addClass(document.body, 'overflowYHiddenImportant');
  this._renderer.removeClass(document.body, 'overflowYHidden');
}

Try this. Why use elementRefs? Just use [ngStyle]

<div [ngStyle]="{ 'overflowY' : 'hidden !important' }"></div>

or

<div [style.overflowY ]="'hidden !important'"></div>

Also, if it happens automatically on load (in ngOnInit), why not simply hardcode it in your template? And why don't you simply use CSS and add it with Angular?

Related