How to add | remove css class in angular element?
Access to angular element is via: this.elementRef.nativeElement (import { ElementRef } from '@angular/core';).
CSS class name is myclass.
There are two ways of doing do one by using (ElementRef, Renderer) or by using Hostbinding Below example demonstrate to add and remove the class based on a click event Hostbinding eg: with help of variable, I am attaching an open(instead of open you can even add your class name) class to the HTML element.
import { Directive, ElementRef, HostListener, HostBinding } from '@angular/core';
@Directive({
selector: "[appDropDown]",
})
export class DropdownDirective {
@HostBinding('class.open') isOpen = false;
constructor(private elRef: ElementRef) {
}
@HostListener('click') click(eventData: Event) {
this.isOpen = !this.isOpen
}
}
ElementRef eg: Below example is for the Add method when you are using renderer
import { Directive, ElementRef, HostListener, Renderer2, } from '@angular/core';
@Directive({
selector: "[appDropDown]",
})
export class DropdownDirective {
constructor(private elRef: ElementRef, private renderer: Renderer2) {
}
@HostListener('click') click(eventData: Event) {
this.renderer.setAttribute(this.elRef.nativeElement, 'class', 'open');
}
}
if you are not using renderer then for direct native element u can use this.elementRef.nativeElement.classList.add('class')
Note:Renderer2 is for angula6 version though`