2

我想激活multiple下拉菜单中的选择选项以将多个值存储在数组中,但出现错误:

UsermanagementCreateComponent.html:6 ERROR 错误:如果选择被标记为多个,则无法分配单个值

组件.html

      <div class="form-group row">
          <label for="inputRole" class="label col-sm-3 col-form-label">Role</label>
          <ng-container *ngIf="_userRoles$ | async as roles">
            <!-- <div class="col-sm-3"> -->
              <nb-select multiple placeholder="Multiple Select" formControlName="roles">
                <nb-option *ngFor="let role of roles" [value]='role._id'>{{role._id}}</nb-option>
              </nb-select>
            <!-- </div> -->
          </ng-container>
        </div>

组件.ts

export class UsermanagementCreateComponent implements OnInit {

  createUserForm: FormGroup;
  private _userRoles$: Observable<Role[]>;
  roles: any;

  constructor(private _http: HttpClient,
    private _usersService: UsersService,
    private _roleService: RoleService,
    private _router: Router,
    private _formBuilder: FormBuilder) { }


  ngOnInit() {
    this.loadRoles()
    this.createUserForm = this._formBuilder.group({
      username: [''],
      firstName: [''],
      lastName: [''],
      email: [''],
      password: [''],
      roles: [''],
    })
  }

  loadRoles() {
    this._userRoles$ = this._roleService.getRoles();
  }
4

1 回答 1

3

由于 formControlroles应该是一个数组,因此您的表单组最初需要设置多个值。

private createUserForm: FormGroup;
private initialState = {
  username: '',
  firstName: '',
  lastName: '',
  email: '',
  password: '',
  roles: []
};

createForm() {
  this.createUserForm = this._formBuilder.group({
    username: [this.initialState.username],
    firstName: [this.initialState.firstName],
    lastName: [this.initialState.lastName],
    email: [this.initialState.email],
    password: [this.initialState.password],
    roles: [this.initialState.roles]
  })
}

resetForm() {
  this.createUserForm.reset(this.initialState);
}
于 2019-08-11T18:59:19.103 回答