Angular :如何以编程方式将 css 样式设置为 body 在打字稿中很重要

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

在我的 angular 应用下

我正在使用此代码设置自定义主体样式:

  constructor(private elementRef: ElementRef) { }

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

对于某些特定的场景,我必须添加 “重要”

这将是这样的:

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

但这不起作用,并且“important 没有添加到样式中。

注意;因为我需要将它应用到主体本身,而不是应用到组件之外的特定 html 元素,ngStyle 无法做到。

建议??

试试这个。为什么要使用 elementRefs?只需使用 [ngStyle]

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

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

此外,如果它在加载时自动发生(在 ngOnInit 中),为什么不简单地将其硬编码到您的模板中呢?为什么不简单地使用 CSS 并添加 Angular?

This 应该可以。

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

当你需要在body中添加一个class时,Renderer2是一个不错的选择。首先创建 2 classes:

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

现在使用渲染器:

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

// class declaration skipped

_renderer: Renderer2;

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

我不知道你用什么逻辑什么时候用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');
}

html:

<h2 #elem>hiper king</h2>

ts:

从“@angular/core”导入{组件、ViewChild、Renderer2、ElementRef、AfterViewInit};

@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');
  }
}

试试这个

参考: