简体   繁体   English

在Angular中使用jQuery添加或删除DOM类

[英]Add or remove DOM classes with jQuery in Angular

I am migrating an AngularJS app to Angular 2+. 我正在将AngularJS应用迁移到Angular 2+。 How should I implement the below code in Angular 2+ in order to add or remove CSS classes to the DOM: 为了在DOM中添加或删除CSS类,我应该如何在Angular 2+中实现以下代码:

link(scope, element, attrs) {
  let app = angular.element(document.querySelector('#app'))
  element.on('click', (event) => {
    if (app.hasClass('nav-collapsed-min')) {
      app.removeClass('nav-collapsed-min')
      this.collapseService.notify(false)
    } else {
      app.addClass('nav-collapsed-min')
      this.collapseService.notify(true)
    }
    return event.preventDefault()
  })
}

use ngClass in your html. 在html中使用ngClass。 eg: 例如:

<div [(ngClass)] = "{'your-class-name': condition}"></div>

in order to change the class of an object, you can use angular ngClass directive like this example or using renderer2 as part of an onClick method in the ts file as explained here . 为了改变对象的类,则可以使用角ngClass指令这样例子或使用renderer2如在TS文件一个onClick方法的一部分所说明这里 Be aware that you have to use renderer2 and not renderer (which is deprecated). 请注意,您必须使用renderer2而不是renderer(已弃用)。

From angular document : 从角度文件

" Avoid direct use of the DOM APIs The built-in browser DOM APIs don't automatically protect you from security vulnerabilities. For example, document, the node available through ElementRef, and many third-party APIs contain unsafe methods. Avoid directly interacting with the DOM and instead use Angular templates where possible. " 避免直接使用DOM API 内置的浏览器DOM API不会自动保护您免受安全漏洞的影响。例如,文档,通过ElementRef可用的节点以及许多第三方API均包含不安全的方法。请避免与之直接交互DOM,并尽可能使用Angular模板。

I finally use the import {DOCUMENT} from '@angular/platform-browser'; 我最终使用了import {DOCUMENT} from '@angular/platform-browser';import {DOCUMENT} from '@angular/platform-browser'; to manipulate my DOM and implement my function like this: 操纵我的DOM并实现我的功能,如下所示:

 link(scope?, element?, attrs?) {
   const app = this.document.querySelector('#app');
   if (app.classList.contains('nav-collapsed-min')) {
      app.classList.remove('nav-collapsed-min');
      this.collapseService.notify(false);
   } else {
      app.classList.add('nav-collapsed-min');
      this.collapseService.notify(true);
   }
 }

So that worked great for me. 所以这对我来说很棒。

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

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