11

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.

0

3 Answers 3

15
constructor(public elementRef: ElementRef, private renderer: Renderer)
{
        this.renderer.setElementClass(this.elementRef, 'class');
   // or 

            this.elementRef.nativeElement.classList.add('class');

}
  1. Using Renderer
  2. Using addClass on Native element
Sign up to request clarification or add additional context in comments.

Comments

4

You can use HostBinding to do that, without using a Renderer or ElementRef. See this example :

import {Component, HostBinding} from "@angular/core";

@Component({
   ...
})
export class myComponent {
    @HostBinding('class.myclass') visible: boolean = false;  // True when visible
}

Comments

3

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`

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.