htmlangulardata-bindingmodel

How to update the child of a model based on a select option


My question might feel stupid but I got this model :


export interface Role {
  id: number;
  rolename: string;
  permissions: string;
  createdAt: string;
  updatedAt: string;
}

export interface User {
  id: number;
  username: string;
  createdAt: string;
  updatedAt: string;
  Role: Role;
}

And I want to create a form to update the role based on the list of roles I have.

I have tried this:

<label for="roleId" class="form-label">Role:</label>
<select name="" [(ngModel)]="selectedUser.Role" (change)="onRoleChange()">
    <option *ngFor="let role of roles" [value]="role">{{ role.rolename }}</option>
</select>

But I got an error : Object is possibly 'null'.ngtsc(2531)

I didn't find any good advice online, should I use a 2nd variable as 'selectedRole' and bind this value or should I create a child component to deal with it ?

I tried to change it to

<select name="" [(ngModel)]="selectedUser?.Role" (change)="onRoleChange()">
    <option *ngFor="let role of roles" [value]="role">{{ role.rolename }}</option>
</select>

Or change the model as


export interface Role {
  id: number;
  rolename: string;
  permissions: string;
  createdAt: string;
  updatedAt: string;
}

export interface User {
  id: number;
  username: string;
  createdAt: string;
  updatedAt: string;
  Role?: Role;
}

But it does not get any better.


Solution

    1. When you define the selectedUser use

      selectedUser:User={} as User
      
    2. or, if you define like

      selectedUser!:User
      

      use a "if"

      @if(selectedUser)
      {
         ...
         <select name="" [(ngModel)]="selectedUser.Role" >
      }
      

    BTW: generally you only need store in the user the "role.id"