Search code examples
angularselectngmodel

Angular Two-Way binding using NgModel not updating value


I'm trying to implement a select box in Angular to be able to switch between orders. I'm also having a generic table that takes an api Url to get that specific order. The api url is built together within the ts file and contains the orderId which I'm trying to bind using [(ngModel)]. When I switch between orderIds using the select box, I want the table to be updated.

When I'm using the following implementation, the {{orderId}} is updating when I change the select box, but the {{orderFilesApi}} (and table data) isn't.

Do you have an idea what I am doing wrong?

.ts file:

@Input() orderId = '123';
@Output() orderFilesApi = this.serverUrl + '?' + 'orderid=' + this.orderId;

orders: Orders[] = [
   {value: '123', viewValue: 'ORDER1'},
   {value: '456', viewValue: 'ORDER2'}
];

.html file:

<mat-form-field>
  <mat-select placeholder="Change Order" [(ngModel)]="orderId">
    <mat-option *ngFor="let order of orders" [value]="order.value">
      {{order.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<div>{{orderId}}</div>
<div>{{orderFilesApi}}</div>

<app-data-table
  [apiUrl]="orderFilesApi"
  [displayedColumns]="['name', 'type']">
</app-data-table>

Solution

  • Looking into the code you posted there could be two reasons:

    1. If

      <app-data-table [apiUrl]="orderFilesApi" [displayedColumns]="['name', 'type']"> </app-data-table>

      in different html

      do like

      this.orderFilesApi.emit(this.serverUrl + '?' + 'orderid=' + this.orderId);

      in the change event.

    2. If

      <app-data-table [apiUrl]="orderFilesApi" [displayedColumns]="['name', 'type']"> </app-data-table>

      in same html

      change output property to normal one like @output() orderFilesApi to simple property and set

      this.orderFilesApi = this.serverUrl + '?' + 'orderid=' + this.orderId

      in the change event.