0

If you use a framework such as bootstrap, you know that an element classes change depending on actions or viewport size...

Is there an event in Angular that allows us to detect when the classes of an element change?

For example, having a bootstrap navbar, each time it has show class in its class list I want to console.log("show"), and each time it doesn't have show class in its class list I want to console.log("hide"). In other words, I want to subscribe to the class change of the element.

EddyG
  • 2,051
  • 3
  • 22
  • 46

1 Answers1

-1

You could detect a class change by using EventEmitter to emit the change. You'll need to subscribe to it before emitting. See the following example, hope that helps:

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

@Component({
  selector: 'my-app',
  template: `
    <p [ngClass]="{ active: active }">
      The active text
    </p>
    <button (click)="isActive($event)">change class</button>
  `,
  styles: [`
    .active {
      background-color: yellow;
    }
  `]
})

export class AppComponent {
  active = false;
  activate: EventEmitter<boolean> = new EventEmitter();

  isActive(event) {
    this.active = !this.active;
    this.activate.emit(this.active);
  }

  ngOnInit() {
    this.activate.subscribe((data) => {
      console.log('active: ' + data);
    })
  }
}
Aloysius
  • 49
  • 8
  • I do not want to detect it using the click event or an alternative event. I want to detect it on the element itself. – EddyG Jul 08 '19 at 09:04
  • I'm not aware of a built-in event in angular that gives you info about a component's class change. I imagine you'll have to build that mechanism yourself. You could have a child component that emits 'classChanged' along with the class that changed (eg. 'show'). Then in the parent component, you can handle that via a listener function. – Aloysius Jul 09 '19 at 14:06