简体   繁体   中英

Add or remove DOM classes with jQuery in Angular

I am migrating an AngularJS app to Angular 2+. How should I implement the below code in Angular 2+ in order to add or remove CSS classes to the DOM:

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. 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 . Be aware that you have to use renderer2 and not renderer (which is deprecated).

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. "

I finally use the import {DOCUMENT} from '@angular/platform-browser'; to manipulate my DOM and implement my function like this:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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