I'm learning Angular. I've created a widget. I'm using primeng component i.e. p-overlaypanel. The panel opens up when I click on an input field. I have two buttons Apply and Cancel inside the overlaypanel itself. I want this overlay to get closed when I click on cancel button. Here is the stackblitz. And here is my code.
timeselector.component.html
<div class="timeselector">
<p-overlayPanel class="timeselector-overlay" #op>
<div class="timeselector-panel">
<p>Time selector</p>
<br />
<div>
<button (click)="closeTimeselector($event, op)">
Cancel
</button>
<button>
Apply
</button>
</div>
</div>
</p-overlayPanel>
</div>
<div (click)="op.toggle($event)">
<input type="text">
</div>
And timeselector.component.ts
import { ... } from '@angular/core';
@Component({
...
})
export class TimeselectorComponent implements OnInit {
timeselectorOpen = false;
constructor() {}
ngOnInit(): void {}
closeTimeselector(event, element) {
if (this.timeselectorOpen) {
element.hide(event);
this.timeselectorOpen = false;
}
console.log("closer called");
}
}
One of the possible solution is to use:
<button (click)="op.hide()">
Cancel
</button>
But I cannot do so beacuse I've to do some cleanup task and flush some values when that widget is closed.
The function is called, that I've checked on console. But the overlay is not collapsing back. You can directly go to the stackblitz. Please correct me.
Your problem is the condition "if" in the "closeTimeselector" function. The variable "timeselectorOpen" never changes, but is checked in the condition and is always "false".
I think, you don't control timeselectorOpen
import { ... } from '@angular/core';
@Component({
...
})
export class TimeselectorComponent implements OnInit {
timeselectorOpen = false;
constructor() {}
ngOnInit(): void {}
closeTimeselector(event, element) {
element.hide(event);
console.log("closer called");
} }
Please try this code.
Using Viewchild in the above situation might the best as it gives you more control over the functions
@ViewChild('op', {static: false}) model;
(According to angular 8). In Previous versions syntax was different, you dont need to give {static:false}.
closeTimeselector(event) {
this.model.hide();
if (this.timeselectorOpen) {
this.timeselectorOpen = false;
}
console.log("closer called");
}
By using Viewchild you will always have a reference for the template, so you will get more control in your TS file.
Based on the documentation
https://www.primefaces.org/primeng/#/overlaypanel
toggle, show, hide are the methods
So you can simply add
<button (click)="op.hide()">
Cancel
</button>
working example here: