1

How to add or remove CSS classes to HTML elements when I click on them in Angular7? I want to achieve this without using Ng-Style and Ng-Class directives.

Thanks in advance.

0

2 Answers 2

1

I think it's something like this what you want to achieve (to add and remove a Class on click):

clicked(event) {
let oldClass = event.target.getAttribute('class');
if (oldClass == null) {
  oldClass = '';
  this.render.setElementAttribute(event.target, "class", oldClass + 'selected');
} else if (oldClass.includes('selected')) {
  oldClass = oldClass.replace('selected', '')
  this.render.setElementAttribute(event.target, "class", oldClass);
} else {
  this.render.setElementAttribute(event.target, "class", oldClass + ' selected');
}

Don't forget to import { Renderer } from '@angular/core'; and add constructor(private render: Renderer) { }

See the Stackblitz Demo

More info about Renderer and .replace() or .replace()

Sign up to request clarification or add additional context in comments.

Comments

0
import { Directive, HostBinding} from '@angular/core';

@Directive({
  selector: '[myDirective]',
})
export class MyDirective {

  @HostBinding('class')
  elementClass = 'custom-theme';

  constructor() {
  }
}

then just use it like

<div myDirective> </div>

For directly using inside component

import {Component, Renderer2} from '@angular/core';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent  {

  constructor(private renderer: Renderer) {}

  click(event) {
    renderer.addClass(event.target, 'popup');
  }
}

1 Comment

Thanks. But I want to call a function in the '(click)' event and add the classes via that function? (maybe using ElementRef)

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.