Search code examples
angularangular-materialangular7angular8

Detect focus lost from different input in Angular 8?


I have 2 inputs, one of them has a numeric value on it:

<input matInput class="form-control"
                [(value)]="row.value"
                ([ngModel])="row.value">

The second input calculates that value -20€ value.

<input matInput class="form-control"
                value="{{ row.value - 20 | round }}"
                ([ngModelChange])="row.value">

And I also apply a round filter. The result is this:

enter image description here

When I change the value on the first input (column Retail value), I would like to be able to capture it from the second input (Total cost) and recalculate it. The most angularish way possible.

So my question is:

What is the best Angularish way to do this?

Edit: I should have said that my inputs are located insidte a material table:

<mat-table [dataSource]="dataSource" class="table">
    <ng-container matColumnDef="value">
       <mat-header-cell *matHeaderCellDef > Retail Value </mat-header-cell>
       <td mat-cell *matCellDef="let row">
          <input matInput class="form-control"
                [(value)]="row.value"
                ([ngModel])="row.value"
                (ngModelChange)="updateTotal(row)">
       </td>
    </ng-container>
    <ng-container matColumnDef="value">
       <mat-header-cell *matHeaderCellDef > Retail Value </mat-header-cell>
       <td mat-cell *matCellDef="let row">
          <input matInput class="form-control"
                [(value)]="row.total">
       </td>
    </ng-container>
</mat-table>

And my .ts function:

updateTotal(row: RepairItem) {
   row.total = row.value - row.discount;
}

Solution

  • You are currently 2-way binding the input value to your model using [(ngModel)]. To listen to value changes you can handle (ngModelChange) events.

    component.html

    <input matInput class="form-control"
                    [(ngModel)]="row.value"
                    (ngModelChange)="onModelChange(row)">
    

    component.ts

    onModelChange(row) {
      // row.value has been updated to the new value
      // you also have a reference to the original row, 
      //   should you need to do anything with it
      console.log(row.value);
    }