I am attempting to bind and unbind a HostListener click event based on a component's input variable.
The component is a popup which has a single input called show. This input holds the active/inactive state of the popup. I would like to fire a click event on the entire document but only when the input show is set to true.
Is there a way to bind and unbind the hostlistener event inside the ngOnChanges function I have?
The current code I have:
import {Component, OnInit, Input, ViewEncapsulation, HostListener} from '@angular/core';
@Component({
selector: 'custom-popup',
templateUrl: './popup.component.html',
styleUrls: ['./popup.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class PopupComponent implements OnInit {
@Input() show: boolean = false;
constructor() {
}
ngOnInit() {
}
@HostListener('document:click', ['$event.target'])
clickHandler(targetElement) {
// Custom code to handle click event
}
ngOnChanges(show: boolean) {
if (this.show) {
// Bind Click Event
}
else {
// Unbind Click Event
}
}
}
Any assistance and insight would be greatly appreciated.
showwith a click event on a separate button the HostListener click event fires. The event fires after theshowinput has changed not before. - Carltonshowthen? Set and clear that flag in thengOnChanges()handler, and hopefully that means the order you want things to happen in will be enforced. - GregL