angular - Adding a class to a DOM element when clicked

Since Tyler's answer, things have changed a bit. Renderer is depreciated and replaced by Renderer2. In Renderer 2, the class setElementClass is replaced by addClass. And the new function signature for addClass, according to the docs is

addClass(el: any, name: string): void

So the updated menuToggle function should read

menuToggle(event:any) {
    this.renderer.addClass(event.target,"opened");
}

To accomplish what you want, you will need to use the Renderer(injecting it into the constructor with private renderer: Renderer). The Renderer provides an abstraction over native elements and provides a safe way to interact with the DOM.

In your template, you should be able to do something like this:

<div (click)="menuToggle($event)"></div>

This captures the click event and passes it to the menuToggle function.

Then in your component, you should be able to interact with the DOM using the Renderer like this:

menuToggle(event:any) {
    this.renderer.setElementClass(event.target,"opened",true);
}

The function signature for setElementClass, according to the docs is setElementClass(renderElement: any, className: string, isAdd: boolean) : void

For further reading on the Renderer, this is a good article on Medium. In talking about using the ViewChild and accessing the DOM through the nativeElement compared to using the Renderer, it says:

This works fine(using nativeElement from a ViewChild). We are grabbing the input element with the help of the ViewChild decorator and then access the native DOM element and call the focus() method on the input.

The problem with this approach is that when we access the native element directly we are giving up on Angular’s DOM abstraction and miss out on the opportunity to be able to execute also in none-DOM environments such as: native mobile, native desktop, web worker or server side rendering.

Remember that Angular is a platform, and the browser is just one option for where we can render our app.

Hope this helps.

Tags:

Angular