简体   繁体   English

Angular4-如何从文档主体中删除由引导程序注入的类?

[英]Angular4 - How to remove a class that is injected by bootstrap from the document body?

I am using a 3rd party plugin (ngx-modialog) that has a plugin architecture and I am using its Bootstrap plugin. 我正在使用具有插件体系结构的第三方插件(ngx-modialog),并且正在使用其Bootstrap插件。 Unfortunately there is a bug that after you use it to open a modal window, it does not remove a class from the body tag. 不幸的是,有一个错误 ,在您使用它打开模式窗口后,它没有从body标签中删除类。

I can remove it myself after the user clicks the modal using jQuery: 用户可以使用jQuery单击模式后,我可以自己删除它:

jQuery('body').removeClass('modal-open');

But I would like to know how can I do the exact same as the above line in Angular? 但是我想知道如何与Angular中的上述代码完全相同?

I found I could do this to get a ref to the body: 我发现我可以这样做来获得对身体的参考:

let body = document.getElementsByTagName('body');

I was hoping that might expose a removeClass method. 我希望这可能会公开removeClass方法。 There must be a simple way to do this, so I can abide by the rule of NO JQUERY in Angular! 必须有一种简单的方法来执行此操作,因此我可以遵守Angular中NO JQUERY规则 ;) ;)

NOTE 注意

I am NOT looking to use [ng-class] as I have nothing I can bind to in this scenario. 我不想使用[ng-class],因为在这种情况下我没有什么可以绑定的。

To do that in Angular 4, you can use the Renderer2 class 为此,可以在Angular 4中使用Renderer2类

Use the method: removeClass(el: any, name: string): void 使用方法: removeClass(el:any,name:string):void

Renderer2 is an abstraction provided by Angular to manipulate elements of your app without having to touch the DOM directly Renderer2是Angular提供的一种抽象,用于处理您的应用程序元素, 而无需直接接触DOM

You can import Renderer2 like this: 您可以像这样导入Renderer2:

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

Inject it in the constructor of your component: 将其注入到组件的构造函数中:

constructor(private renderer: Renderer2){
}

Remove a class: 删除课程:

this.renderer.removeClass('body', 'modal-open');

As pointed out in the comments, the 'body' is outside of the domain of Angular - Angular loads its component hierarchy inside it. 正如评论中指出的那样,“ body”不在Angular的域之内-Angular在其内部加载其组件层次结构。

So therefore I just need to fall back to regular javascript to do this: 因此,因此我只需要退回常规javascript即可:

document.body.className = document.body.className.replace('modal-open','');

Thanks to this question . 由于这个问题 No jQuery needed. 无需jQuery。 But the accepted answer is the 'angular way' to do this, which is what I was after. 但是公认的答案是做到这一点的“角度方法”,这正是我所追求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM