TypeScript FormGroup包含下拉列表

时间:2017-11-14 07:09:25

标签: angular typescript angular-reactive-forms

我有一个角色类,如: 作用:

export class Role{
    id:number;
    roleName:string;
    description:string;

}

并指定角色:

import {Role} from './roles';
    export class AssignRole{
        isActive:number;
        userRole:Role= new Role();

    }

在ts文件上,我声明了表单:

this.userForm = new FormGroup({
      userName: new FormControl('', Validators.required,),
      firstName: new FormControl('', Validators.required),
      roles: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),
      address: new FormControl('', [ Validators.required,])
    });

在html中,我想创建角色dopdownlist

<div class="form-group">
                      <label>Roles</label>
                      <select  class="form-control" id="roles">
                         <option formControlName="roles">

                         </option>

                     </select>
                    </div>

并将数据输入到角色字段:

this.route.params.switchMap((params: Params) => this.userService.getAssignRole(+params['id'])).subscribe(
        assignRole => {
          this.userForm.patchValue({
            roles:assignRole.userRole.roleName
          });
        }, error => {
          console.log(error);
        }
      );

显示错误消息:错误错误:没有名称形式控件的值访问器:'roles'

请建议我。

1 个答案:

答案 0 :(得分:0)

您需要更改HTML,以便formControlName位于<select>标记内。 然后我认为你需要一个默认值,所以你没有空白字段。

以下是选择性别的示例:

在您的HTML中:

<select class=form-control formControlName="gender" required>
    <option value="F">F</option>
    <option value="M">M</option>
</select>

在app.component.ts中,设置默认值:

this.form= fb.group({
    gender: new FormControl('F'),
    ...
});