Reputation: 224
I have object in Angular component which is created like this:
calendarValues = { startDate: new Date(), endDate: new Date() };
on ngOnInit
I am fetching data from backend and assigning values to this object:
this.calendarValues.startDate = new Date(this.leaveRecordForEdit.leaveStart);
this.calendarValues.endDate = new Date(this.leaveRecordForEdit.leaveEnd);
and that object calendarValues is forwarded to child component which displays 2 date dropdowns with [calendarValues]="calendarValues"
and in child component I am using @Input() calendarValues: any;
and again on ngOnInit
I am assigning those dates to variables to be binded to html:
this.startDate = this.calendarValues.startDate;
this.endDate = this.calendarValues.endDate;
When testing I have following issue:
Second dropdown (10/3/2024) is showing correct value -value from db. Ouptut to json for startDate, endDate and calendarValues is just showing current date
Interestingly console log for calendarValues is giving:
Console output in constructor is null for calendarValues
, but on ngInit
is a bit weird, on the first line of object in console I have for startDate
value Oct 25 2024 but in expanded object startDate
is has value of Oct 3, which is correct value from the database and it is got bind correctly to second drop-down, Same issue with values is happening for endDate
in console with one difference 10/25/2024 is shown in html ?
So any thoughts on this? Can anyone explain in detial what is happening here?
Upvotes: 1
Views: 38
Reputation: 224
Hi detectChanges did not have desired effects. But thing was that view was ready before actual data processing was done. So issue was fixed by delaying rendering of actual component view after the data processing was done.
Upvotes: 0
Reputation: 56522
You probably have change detection set to OnPush
that is why the changes are not detected, try trigger manual Change detection using ChangeDetectorRef
method detectChanges
, when the values are updated, this will propagate the changes up the component and mostly solve the issue.
You probably logged the console before the values were set.
Pre collapse is a snapshot of the object, so it is showing the current date since that was the default value set on the object, before the proper values were assigned.
When you open it, it reads the memory reference, which has the latest value in the object, hence it might be showing the correct value.
You will not face this issue for primitive types (string, number, boolean, etc.) only for non primitive types that are stored as memory references (array and object).
Upvotes: 0