3
<form #form="ngForm" (ngSubmit)="formSubmit(form.value)">
    <nb-select name="select" ngModel multiple>
        <nb-option value="1">Item 1</nb-option>
        <nb-option value="2">Item 2</nb-option>
        <nb-option value="3">Item 3</nb-option>
        <nb-option value="4">Item 4</nb-option>
    </nb-select>
</form>

When I add "multiple" to the nb-select, following error arises:

ERROR Error: Uncaught (in promise): Error: Can't assign single value if select is marked as multiple

I'm not angular expert, so I'm not sure but I think the issue is because angular is trying to assign an array of values to a string typed variable.

If I remove "multiple", it works fine. Also if I remove "ngModel" it throws no error, but then I can't access it's value in formSubmit().

Can you help me to fix this issue, please?

Thank you.

velediqa
  • 53
  • 7
  • 1
    According to [this](https://github.com/akveo/nebular/issues/1950) thread this is known issue. – robert Jul 07 '21 at 10:41

1 Answers1

1

With reactive forms approach it works.

In app module import: import { ReactiveFormsModule } from '@angular/forms';

Add to imports array ReactiveFormsModule

Change your html

<form [formGroup]="frm" (ngSubmit)="onSubmit()">
  <nb-select formControlName="models" multiple>
      <nb-option value="1">Item 1</nb-option>
      <nb-option value="2">Item 2</nb-option>
      <nb-option value="3">Item 3</nb-option>
      <nb-option value="4">Item 4</nb-option>
  </nb-select>
  <button type="submit">Submit</button>
</form>

create a FormGroup in TS file:

  frm: FormGroup;

  constructor(fb: FormBuilder) {
    this.frm = fb.group({
      models: []
    });
  }

onSubmit:

  onSubmit() {
    console.log(this.frm.value);
  }
robert
  • 5,742
  • 7
  • 28
  • 37
  • 1
    Thank you sir, It works like a charm! Isn't there another approach out there so that it automatically creates FormGroup? I mean, with less codes in ts files, maybe more codes in html files, like what I posted in my question. This is my first project in angular and there is a lot of forms that I need to create, writing and maintaining less codes in ts files makes it really a life saver for me. Thank you again for the help. – velediqa Jul 08 '21 at 07:35
  • @velediqa Check this [answer](https://stackoverflow.com/a/41685151/2050306) for quick comparison and a bit older [video](https://www.youtube.com/watch?v=xYv9lsrV0s4). My recommendation is to invest into Reactive Forms it will benefit on a long run. – robert Jul 08 '21 at 10:06
  • 1
    I'll go with Reactive Forms. Thank you. – velediqa Jul 09 '21 at 12:32