gpt4 book ai didi

Angular2检测模板 View 中的元素是否具有类

转载 作者:太空狗 更新时间:2023-10-29 16:51:44 24 4
gpt4 key购买 nike

我们正在使用 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) { }
}

这是我的 View 模板的一部分:

<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 不确定是否相关。

最佳答案

添加一个模板变量以便能够查询元素。

<div #patientDDL class="overlay-dropdown dropdown" id="patientDDL">

查询元素

@ViewChild('patientDDL') patientDDL:ElementRef;

执行 ngDoCheck() 以在更改检测运行时运行检查是否添加了该类:

ngDoCheck() {
if(patientDDL.nativeElement.classList.contains('open')) {
this.doSomething();
}
}

或在某些特定事件上

@HostListener('click', ['$event'])
clickHandler(event) {
if(patientDDL.nativeElement.classList.contains('open')) {
this.doSomething();
}
}

关于Angular2检测模板 View 中的元素是否具有类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38018891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com