0

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()
  })
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Manu
  • 1,065
  • 14
  • 21
  • 1
    don't use `querySelector` or `jQuery` in your Angular 2, is not need and it might break your code if you want to use SSR later on. Take a look to this post https://blog.angularindepth.com/exploring-angular-dom-abstractions-80b3ebcfc02. Anyway, most of this cases where you just want to toggle class can be done with `ngClass` directive – nicowernli Feb 19 '18 at 14:59

3 Answers3

0

use ngClass in your html. eg:

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

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

Omtechguy
  • 3,321
  • 7
  • 37
  • 71
0

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.

Manu
  • 1,065
  • 14
  • 21