Angular2 selected option with objects

Issue

I have an Angular 2 app that is dealing with customers and a spring rest back end. The customer object has a customer type, which is also an object, and I have the drop down on the customer form working so that objects are stored as the value, however I can’t figure out how to select the correct customer type when an existing customer is loaded into the form.

<select  class="form-control" required [(ngModel)]="customer.customerType" >
   <option *ngFor="let ct of customerTypes" [ngValue]="ct">{{ct.customerType}}</option>
</select>

In the above snippet if the customer already has a customer type, then the dropdown won’t select any value. I remember having the same problem with angular1 which was solved using ngOptions:

<select ng-model="customer.customerType"
        ng-options="customerType.customerType for customerType in customerTypes 
        track by customerType.customerType" >
</select>

So, my question is, how to replicate the way Angular1 solved this problem in Angular 2

Solution

I’ve taken the slightly clunky approach of replacing the instance of CustomerType that is returned in my Customer object, with that held in the CustomerType array. This can only be done once both the Customer and CustomerTypes have been returned from the backed:

ngOnInit() {
    let id = this._routeParams.get('id');
    this._service.getCustomer(id).subscribe(customer => {
      this.customer = customer;
      this.updateCustomerType();
    });
    this._service.getCustomerTypes().subscribe(customerTypes =>{
      this.customerTypes = customerTypes;
      this.updateCustomerType();
    });
}
private updateCustomerType(): void{
  if(this.customer.customerType != null && this.customerTypes.length != null){
    for (var customerType of this.customerTypes) {
      console.log("Customer Type: ", customerType);
      if(this.customer.customerType.id == customerType.id){
        this.customer.customerType = customerType;
      }
    }
  }
}

Answered By – Drew

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.