【发布时间】:2016-10-27 09:32:32
【问题描述】:
我们使用引导程序,有时它会自动将类添加到 DOM 元素。附加到这些元素并检测何时将particalr 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”类添加到#patientDDL 元素并在我的组件中执行函数时,我如何在我的组件中进行检测?
谢谢!
编辑: 我根据 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 不确定是否相关。
【问题讨论】:
标签: angular