'p-calendar angular 6 event onClick doesnt fire (and others events)
I want to call a method when I open a component, so I've tested some method, no one works just (onSelect) event works. Here is a part of the code :
<p-calendar id="idCalendarDateExportFrom" [showIcon]="true" [(ngModel)]="dateChoosenProd" readonlyInput="true" [showTime]="true" dateFormat="dd/mm/yy" [locale]="fr"
(onClick)="moveDate(1)" (onSelect)="moveDate(0)">
</p-calendar>
In ts file :
public moveDate(position: Number){
if(position === 1){
this.marginTop = "400px";
} else {
this.marginTop = "0px";
}
}
I've tried also onclick without uppercase, onmouseover, ...
I use Angular 6
Solution 1:[1]
calendar
component of PrimeNG uses an input
tag to display the date input box. So theoretically, you could bind to it's mouse events. The following works partially as requested. But for some reason, the onmousedown
event is triggered again when the onSelect
event is triggered.
<p-calendar [(ngModel)]="value" [locale]="en" (mousedown)="moveDate(1)" (onSelect)="moveDate(0)"></p-calendar>
Working example: Stackblitz
Solution 2:[2]
Check the Events table in primefaces calendar docs
E.g.:
onShow event: Animation event Callback to invoke when datepicker panel is visible.
or
onSelect value: Selected value Callback to invoke when a date is selected. Note that this event is not called when the value is entered from the input manually.
See Stackblitz
Solution 3:[3]
<p-calendar
[(ngModel)]="testDate"
(onSelect)="selectDate()"
(onBlur)="blurDate()">
</p-calendar>
If i used both onBlur
and onSelect
on the same input with [(ngModel)]
they both get called after picking day from calendar, but inside onBlur
variable inside ngModel was undefined! Inside onSelect
same variable had picked day. Some debounce could be good for this.
But as documentation say, onSelect
won't be called if you enter value by hand, then just onBlur
is called - but variable inside ngModel
is updated to picked value!
Also, neither onSelect
or onBlur
called when you enter value and press Enter (at least in my environment), until user click outside element and loose input focus.
Possible solution:
Use Angular FormGroup
HTML template
<p-calendar formControlName="testDate"></p-calendar>
JS
ngOnInit() {
this.form = this.formBuilder.group({
testDate: [new Date(Date.now())],
});
this.form.valueChanges.subscribe(formData => {
console.log('Picked date:', formData.testDate);
// expected output - picked date as Date.prototype
});
}
This is working when:
- picking date from calendar popup
- changing value manually (again, some debounce could be useful)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ruth |
Solution 2 | Mike Gledhill |
Solution 3 | Nomik |