Angular react 形式下拉列表(多个)

标签 angular dropdown angular-reactive-forms nebular

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

UsermanagementCreateComponent.html:6 ERROR Error: Can't assign single value if select is marked as multiple

组件.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();
  }

最佳答案

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

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);
}

关于 Angular react 形式下拉列表(多个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452554/

相关文章:

css - 无法使用异步管道动态应用 CSS 名称

php - 下拉 onchange 调用 PHP 函数

javascript - 使用 Angular 形式更改表单元素

angular - Ionic 3 组件上的防护装置

javascript - ngStyle 适用于 ngFor 中的所有元素

javascript - “悬停”下拉菜单到可点击的下拉菜单(通过媒体查询)

angular - 为什么要使用 ngSubmit 而不是简单的按钮和功能

angular - Angular 4 ReactiveFormsModule 不应该使用 forRoot 模式吗?

javascript - 如何访问 Angular 组件 $postLink 内的元素

ruby - 选择标记 : How to use params to set the selected value?