简体   繁体   中英

How to implement a select list correctly?

How can I implement a selection list using these three models? I do so:

html:

<ng-container [(ngModel)]='user.id' name="id" >
  <select *ngFor="let userRole of userRoles" required>
    <option *ngFor="let role of roles" [ngValue]="role.role_id">
      {{role.name}}
    </option>
  </select>
</ng-container>

But in the end get a duplicate of the "select" component. And I get this error:

ERROR Error: Uncaught (in promise): Error: No value accessor for form control with name: 'id' Error: No value accessor for form control with name: 'id'

Let's start with your model.

export class User {
  constructor(
    public id: number,
    public role: Role,
  ) {}
}

export class Role {
  constructor(
    public id: number,
    public label: string,
  ) {}
}

Now with your select.

<select [(ngModel)]="user.roles">
  <option *ngFor="let role of roles" [ngValue]="role"> {{ role.label }} </option>
</select>

Which gives as a result, this stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM