I have scenario in my project that a common shared service having a common variable (object) to store nested objects. I have to access and update its value in html using NgModel. Optional-chaining applied to nested object to access and update values because it can be null or undefined, but optional chaining is giving error that two-way binding don't support.
<select
class="form-select"
name="font-size"
id="fontSize"
[(ngModel)]="cmServ.settingsData?.styles?.[elemId]"
>
<!-- `Here 'elemId' can be null or undefined.
And I can't set the 'default' value in ts as it will break
the flow of my application.
or
if Id do this it will work
[ngModel]="cmServ.settingsData?.styles?.[elemId]"
(ngModelChange)="cmServ.settingsData.styles[elemId] = $event"
`-->
<option [value]="''">Select</option>
@for(size of fontSize; track size){
<option [value]="size">{{size}}</option>
}
</select>
I have removed the optional chaining form the 'elemId' then its not giving me the error. Only for the first time when its empty.
<select
class="form-select"
name="font-size"
id="fontSize"
[(ngModel)]="cmServ.settingsData?.styles[elemId]"
>
<!--
-->
<option [value]="''">Select</option>
@for(size of fontSize; track size){
<option [value]="size">{{size}}</option>
}
</select>
Here is the link for dummy application:
https://stackblitz.com/edit/stackblitz-starters-t5esi6?file=src%2Fmain.html
Case also to be considered: In my application, 'elemId' is also set to null or empty string from far way/ main page component to reset the fields.
How I should apply the optional chain in the ngModel so the my application also wouldn't break and check also applied.