Angular2将类添加到body标签 [英] Angular2 add class to body tag

查看:262
本文介绍了Angular2将类添加到body标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不将 body 用作应用选择器并使用主机绑定的情况下,将 class 添加到 body 标签?

How can I add a class to the body tag without making the body as the app selector and using host binding?

我尝试使用Renderer,但它会改变整个身体

I tried the using the Renderer but it changes the whole body

body标签上的Angular 2.x绑定类

我正在开发一个大型angular2应用,更改根选择器会影响很多代码,我将不得不更改很多代码

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

我的用例是这样:

当我打开一个模态组件(动态创建)时,我想隐藏文档滚动条

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.

  1. 注入全局文档.嗯,这可能不是最佳做法,因为我不知道nativescript等是否支持该做法.但这至少比使用纯JS更好.


constructor(@Inject(DOCUMENT) private document: Document) {}

ngOnInit(){
   this.document.body.classList.add('test');
}

好吧,也许更好.您可以注入渲染器或渲染器2(在NG4上),然后将类与渲染器一起添加.

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

编辑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标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆