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()
  })
}
1
  • 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 blog.angularindepth.com/…. Anyway, most of this cases where you just want to toggle class can be done with ngClass directive Commented Feb 19, 2018 at 14:59

3 Answers 3

0

use ngClass in your html. eg:

<div [(ngClass)] = "{'your-class-name': condition}"></div>
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.