2

I have a Angular5 <select> bound to array of customers. See below:

<select class="form-control" [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x.id">{{x.name}}</option>
</select>

In setCustomer function I get an customer's id as 'event'.

Property record.customer_id is type of number, not object. Is there any way how to get a whole customer entity in setCustomer method and also preserve binding to record.customer_id ?

I found on Angular docu a way [compareWith] so I tried:

<select class="form-control" [compareWith]="compareCustomer"  [ngModel]="record.customer_id" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>

and

compareCustomer(c1: customer, c2: number) : boolean {
   if (c1 == null || c1 == undefined) {
     return false;
   }

   if (c1.id == c2) {

     return true;
   }

   return false;
}

Does not work. When I select any option, setCustomer is executed, record.customer_id gets selected id. However, after select loses focus, selected option is reset to blank.

There is a workaround (iteration in customers array and manual match by id) that I want to avoid:

 setCustomer(event) {

    this.record.customer_id = Number.parseInt(event);

    customers.forEach(c => {

       if (c.id === this.record.customer_id) {

           // some logic with selected customer


       }
    });
}

Any advice?

Thanks!

1 Answer 1

2

Instead of bind customer_id, bind the whole object:

<select class="form-control" [ngModel]="record" (ngModelChange)="setCustomer($event)" name="customer_id">
  <option *ngFor="let x of customers" [ngValue]="x">{{x.name}}</option>
</select>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.