我们使用 bootstrap,有时它会自动向 DOM 元素添加类。附加到这些元素并检测何时将特定 css 类添加到组件模板子元素的最佳方法是什么?
假设我有这个组件:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { HeaderService } from './header.service';
@Component({
selector: 'header-comp',
templateUrl: './Home/RenderLayoutHeader'
})
export class HeaderLayoutComponent {
constructor(private _headerService: HeaderService) { }
}
这是我的视图模板的一部分:
<header-comp>
<li class="nav-header-icon-list-item">
<div class="overlay-dropdown dropdown" id="patientDDL">
<button class="btn btn-default dropdown-toggle session-menu-container" type="button" id="session-dropdown-menu" data-toggle="dropdown" data-backdrop="true" data-dismiss="modal" aria-haspopup="true" aria-expanded="false">
<img data-initials="ER" src="https://lorempixel.com/40/40/abstract/" class="img-circle session-user-profile-img">
当 bootstrap 将“open”类添加到 #patentDDL 元素并在我的组件中执行函数时,如何在我的组件中进行检测?
Thanks!
编辑:
我根据 Gunter 的解决方案修改了我的组件,但是当我不在标准之前进行空检查时,我得到了空引用)
import { Component, ViewChild, ElementRef, DoCheck } from '@angular/core';
import { HeaderService } from './header.service';
@Component({
selector: 'header-comp',
templateUrl: './Home/RenderLayoutHeader'
})
export class HeaderLayoutComponent implements DoCheck {
@ViewChild('patientDDL') patientDropDownList: ElementRef;
constructor(private _headerService: HeaderService) { }
ngDoCheck() {
console.log('ngDoCheck called');
if (this.patientDropDownList && this.patientDropDownList.nativeElement.classList.contains('open')) {
this._headerService.setPatientDDLOpen(true);
} else {
this._headerService.setPatientDDLOpen(false);
}
}
}
此外,在模板加载时,控制台语句会被记录 4 次,但即使在多次添加/删除类之后,也不会再次调用它。
这是 angular2 rc1 不确定这是否相关。