Anupam Sharma
Anupam Sharma

Reputation: 1

How to implement Optional chaining in ngModel using angular 18

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.

Upvotes: 0

Views: 240

Answers (1)

jaheraho
jaheraho

Reputation: 550

I can't tell you the fix at this moment.

But I have some general recommendation for you.

Don't

  • set attributes of a service within a component.
  • use attributes of a service in a components template.

Do

  • avoid stateful services.
  • if you want to have a stateful service, use getter/setter to access it's attributes.
  • have a dedicated model in your component, which you can use in your template.

If you want, you can rewrite your code considering my recommendations. Maybe it solves your issue in the first place. (Because you don't have chained access of a service variable!). If it doesn't fixes the problem, I will dive into that deeper.

But I refuse to fixes issues with direct access of service attributes within a component template 😉

Upvotes: 0

Related Questions