是否有一个事件可检测角度的模板元素上的类属性更改?

时间:2019-07-07 22:12:45

标签: javascript angular

如果使用诸如引导程序之类的框架,您将知道元素类会根据操作或视口大小而变化...

Angular中是否有一个事件可以让我们检测元素的类何时更改?

例如,有一个引导导航栏,每次它要在其类列表中有show个类时,我想console.log("show"),并且每次它都没有其show类时我要console.log("hide")的班级列表。换句话说,我想订阅元素的类更改。

1 个答案:

答案 0 :(得分:-1)

您可以使用EventEmitter来emit来检测类的更改。您需要subscribe发射它。请参见以下示例,希望对您有所帮助:

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);
    })
  }
}