Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactiveforms Dropdown (multiple)

I would like to activate the multiple option for the selection in the dropdown menu to store multiple values in an array, but I get the error:

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

component.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>

component.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();
  }
like image 342
meai2312 Avatar asked Mar 21 '26 02:03

meai2312


1 Answers

As the formControl roles is supposed to be an array your form group needs to set a multiple value initially.

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);
}
like image 186
Rias Avatar answered Mar 22 '26 21:03

Rias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!