问题描述
如何将 class 添加到 body 标记而不将 body 作为应用选择器并使用主机绑定?
我尝试使用渲染器,但它改变了整个身体
我正在开发一个大型 angular2 应用程序,更改根选择器会影响很多代码,我将不得不更改很多代码
我的用例是这样的:
当我打开一个模态组件(动态创建)时,我希望文档滚动条隐藏
我很乐意发表评论.但由于缺少声誉,我写了一个答案.好吧,我知道解决这个问题的两种可能性.
- 注入全局文档.好吧,这可能不是最佳实践,因为我不知道 nativescript 等是否支持.但至少比使用纯 JS 好.
构造函数(@Inject(DOCUMENT)私有文档:文档){}ngOnInit(){this.document.body.classList.add('test');}
好吧,也许更好.您可以注入渲染器或渲染器 2(在 NG4 上)并使用渲染器添加类.
导出类 myModalComponent 实现 OnDestroy {构造函数(私有渲染器:渲染器){this.renderer.setElementClass(document.body, 'modal-open', true);}ngOnDestroy() {this.renderer.setElementClass(document.body, 'modal-open', false);}针对 ANGULAR4 进行
从@angular/core"导入 { Component, OnDestroy, Renderer2 };导出类 myModalComponent 实现 OnDestroy {构造函数(私有渲染器:Renderer2){this.renderer.addClass(document.body, 'modal-open');}ngOnDestroy() {this.renderer.removeClass(document.body, 'modal-open');}How can I add a class to the body tag without making the body as the app selector and using host binding?
I tried the using the Renderer but it changes the whole body
Angular 2.x bind class on body tag
I'm working on a big angular2 app and changing the root selector will impact a lot of code, I will have to change a lot of code
My use case is this:
When I open a modal component (created dynamically) I want the document scrollbar to hide
I would love to comment. But due to missing reputation I write an answer.Well I know two possibilities to solve this issue.
- Inject the Global Document. Well it might not be the best practice as I don't know if nativescript etc supports that. But it is at least better than use pure JS.
constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit(){ this.document.body.classList.add('test'); }
Well and perhaps even better. You could inject the renderer or renderer 2 (on NG4) and add the class with the renderer.
export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer) { this.renderer.setElementClass(document.body, 'modal-open', true); } ngOnDestroy() { this.renderer.setElementClass(document.body, 'modal-open', false); }
EDIT FOR ANGULAR4:
import { Component, OnDestroy, Renderer2 } from '@angular/core'; export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer2) { this.renderer.addClass(document.body, 'modal-open'); } ngOnDestroy() { this.renderer.removeClass(document.body, 'modal-open'); }
这篇关于Angular2 添加类到 body 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!