简体   繁体   English

如何正确实现选择列表?

[英]How to implement a select list correctly?

How can I implement a selection list using these three models? 如何使用这三个模型实现选择列表? I do so: 我这样做:

html: 的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' 错误:未捕获(承诺):错误:名称为“ id”的表单控件无值访问器错误:名称为“ 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 结果是, 这种堆叠闪电

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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