I'm working on a Angular 14
application in which on a specific scenario where the page load gets the current date (selected from a datepicker
) and pass it to the backend to get the data .
In this case the I trigger the datachange
event manually in ngOnInit
which works on page load or refresh but the event doesn't get fired when the internal navigation/route happens.
//HTML
<input type="date" id="bookedDate" formControlName="bookedDate" [min]="getToday" (change)="changeDate($event)" />
//Typescript
ngOnInit(): void{
const inputElement = document.getElementId('bookedDate) as HTMLInputElement;
if(inputElement){
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
const event = new Event(çhange', {bubbles: true});
//this gets fired in pagerefresh or navigation
inputElement.dispatchEvent(event);
});
});
}
}
changeDate(e:any){
// this event not firing on page navigation
}
Tried multiple options using ngAfterViewInit
, Router
/Route
events subscription but nothing helped.
Where am i wrong?
You have to call the method directly instead, if you want to pass a $event
you have to mock this with the same parameters.
This method is good for test cases where you want the ngModel
to be updated programatically, but since this is actual code, you should just call the method directly and recreate the event
properties you are using.
//Typescript
ngOnInit(): void{
const inputElement = document.getElementId('bookedDate) as HTMLInputElement;
if(inputElement){
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.changeDate({ target: inputElement } as any);
});
}
}
changeDate(e:any){
// this event not firing on page navigation
}