0

I am experiencing some troubles with a select multiple drop-down. I can select multiple values and save them to a in memory api. The only problem is when I want to edit the item and fill the selected items.

I have a working plnkr here. The component is app/trip/trip-creation.component.ts

here is my html:

<select  formControlName="user" multiple>
      <option *ngFor="let user of users" [ngValue]="user">
        {{user.name}}
      </option>
    </select>

here is the form binding:

  this.route.paramMap
              .filter(params => params.get('id') !== null )
              .switchMap(params => this.tripService.getTrip(params.get('id')))
              .subscribe((trip: any) => {
                  this.trip.patchValue({
                    id: trip.id,
                    name: trip.name,
                    user: trip.user
                  });
              })
John
  • 1,697
  • 4
  • 27
  • 53
  • Possible duplicate of [Angular 2, set default value to select option](https://stackoverflow.com/questions/39724161/angular-2-set-default-value-to-select-option) – AT82 Aug 13 '17 at 09:48
  • @AJT_82 I dont think that's duplicate, he doesn't use reactive forms ... – John Aug 13 '17 at 11:09
  • 1
    It doesn't matter if it's ngModel or formControl, the answer is the same :) – AT82 Aug 13 '17 at 11:14
  • 1
    Oh forgot one thing... Are you using v2 or v4 of angular? – AT82 Aug 13 '17 at 11:17
  • @AJT_82 I am using angular v4. I started with angular tour of heroes tutorial. – John Aug 13 '17 at 11:22
  • 1
    Yeah, well then you can use `compareWith` :) – AT82 Aug 13 '17 at 11:25
  • 1
    I'd write you up an answer, but it's not needed here. The code for compareWith is the same as in the duplicate. I tried it with your code and it worked fine. Let me know if you have trouble implementing it! :) – AT82 Aug 13 '17 at 11:35
  • @AJT_82 i'm trying with compareWith but I'm having some troubles, here is my updated plnkr, https://plnkr.co/edit/VYgOKB7GXXdSCGZFKeJg?p=preview. I used this site as a resource: https://angular.io/api/forms/SelectControlValueAccessor – John Aug 13 '17 at 12:48
  • 1
    Okay, what is the problem you are facing? it looks like it's working properly when setting the users? – AT82 Aug 13 '17 at 12:58
  • @AJT_82 You are right, it's working, probably it was some dumb cache issue. They will work on this or anytime I use multiple select I will have to create a function to compare the options? – John Aug 13 '17 at 14:04
  • 1
    It will work for any multiple select, or single select. If you have several different selects on one page, I'd use separate functions though to not encounter problems. – AT82 Aug 13 '17 at 15:09

0 Answers0