这是我的Parent元素html:
<fme-header-icon title="Manage" iconName="class" (click)="triggerPopup(true)">
<fme-pop-up-panel *ngIf="showPopUpManage" (onCloseEvent)='popUpCloseEvent($event)'></fme-pop-up-panel>
</fme-header-icon>
如果用户单击“页眉”图标,它将加载一个弹出窗口。现在,当用户从弹出窗口中单击时,它将关闭。 为此,我在弹出面板(子元素)中通过@Hostlistener创建了一个even,它将检测click事件是否发生在子元素之外。 现在,事件发射器会将其扔到父元素。
import { Component, ElementRef, EventEmitter, Input, OnInit, Output, HostListener } from '@angular/core';
@Component({
selector: 'fme-pop-up-panel',
templateUrl: './pop-up-panel.component.html',
styleUrls: ['./pop-up-panel.component.scss']
})
export class PopUpPanelComponent implements OnInit {
popUpClose: boolean;
@Output() onCloseEvent: EventEmitter<boolean> = new EventEmitter<boolean>();
@Input() title: string;
@HostListener('document:click', ['$event'])
clickout(event) {
if (this._eref.nativeElement.contains(event.target)) {
console.log(event.target);
} else {
this.popUpClose = true; // if click outside it will set to true
this.onOutsideClick();
}
}
constructor(private _eref: ElementRef) {}
ngOnInit() {
}
onOutsideClick() {
this.onCloseEvent.emit(this.popUpClose);
}
}
我想在父元素中做到这一点。
showPopUpManage:boolean= false;
popUpCloseEvent(event: boolean) {
this.showPopUpManage = !event; // if click outsite set to false & close the pop-up
console.log("Hi55", this.showPopUpManage, this.popUpclose);
}
triggerPopupManage(status: boolean) {
this.showPopUpManage = status;
console.log("Hi55", this.showPopUpManage, this.popUpclose);
}
但是它不起作用。你能告诉我如何关闭这个弹出窗口吗?
答案 0 :(得分:1)
问题是您的click事件被调用了两次,首先是孩子,然后是父母。
因此,每次值保持不变。
您必须停止事件的传播,因此事件将在子级停止。
@HostListener('document:click', ['$event'])
clickout(event) {
if (this._eref.nativeElement.contains(event.target)) {
console.log(event.target);
} else {
this.popUpClose = true; // if click outside it will set to true
this.onOutsideClick();
}
event.stopPropagation();
}