在我的角度应用下
我用这个代码来设置一个自定义的身体样式:
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden';
}
对于某些特定的scneario,我必须添加"strong";"重要"到它
这个应该是这样的:
this.elementRef.nativeElement.ownerDocument.body.style.overflowY = 'hidden !important';
但这并不奏效;important没有添加到样式中。
注意;由于我需要将其应用于主体本身,而不是应用于特定的html元素,因此ngStyle无法做到这一点。
建议
这应该可以工作。
this.elementRef.nativeElement.ownerDocument.body.style.setProperty("overflow-y", "hidden", "important");
html:
<h2 #elem>hiper king</h2>
ts:
从"@angular/core"导入{Component、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');
}
}
试试这个
参考:要么我用错了Angular Renerer2,要么它坏了。有人能搞清楚吗?
当您需要向body
添加类时,Renderer2是一个不错的选项。首先创建2个类:
.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);
}
我不知道你在什么时候使用重要的逻辑:
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');
}
试试这个。为什么要使用elementRefs?只需使用[ngStyle]
<div [ngStyle]="{ 'overflowY' : 'hidden !important' }"></div>
或
<div [style.overflowY ]="'hidden !important'"></div>
此外,如果它在加载时自动发生(在ngOnInit
中(,为什么不简单地在模板中硬编码呢?为什么不简单地使用CSS并添加Angular呢?