Yadharth
Yadharth

Reputation: 53

How to achieve react onchange event in angular with ngModelChange

html:

<mat-form-field appearance="outline"class="inputBox">
   <input matInput name="total" placeholder="0.00" [ngModel]="total"
     (ngModelChange)="handleOnChange('total', $event)" />
          </mat-form-field>

TS:

public handleOnChange = (field, e) => {
        console.log("hell", field)
        this.total=90
    }

the value of this.total should remain constant at 90 after any change event triggers the handleOnChange method and 90 should be appear as value in the input box constantly.This is the logic I am trying to achieve, but when there is a onChange at first time, value of input is changed to 90 but after first time when any key is pressed,value is changed. eg. 90a, 90tyhuil, 90oojh....

i come from react. how to achieve the onChange event in input tag of react in angular?

Upvotes: 2

Views: 222

Answers (2)

Naren Murali
Naren Murali

Reputation: 56730

We can just pass the input field directly to function and set the value to the desired result, this will override any changes!

html

<mat-form-field>
  <mat-label>Input</mat-label>

  <input
    matInput
    name="total"
    placeholder="0.00"
    [ngModel]="total"
    #input
    (ngModelChange)="handleOnChange('total', $event, input)"
  />
</mat-form-field>

ts

  public handleOnChange = (field: any, e: any, input: any) => {
    console.log('hell', field);
    this.total = 90;
    input.value = 90;
  };

Stackblitz Demo

Upvotes: 2

Dakshesh Baldaniya
Dakshesh Baldaniya

Reputation: 256

Remove (ngModelChange) event

<mat-form-field appearance="outline"class="inputBox"> 
  <input matInput name="total" placeholder="0.00" [ngModel]="total"/>
</mat-form-field>

Now Initialise total's value in constructor so it will remain same until input change

constructor() { 
  this.total=90
}

Now replace [ngModel]="total" with [(ngModel)]="total" and it will automatically assign new value into total and it will reflect in input and add [value]="total" for reflating initial value into input

So final code will be

<mat-form-field appearance="outline"class="inputBox">
  <input matInput name="total" placeholder="0.00" [(ngModel)]="total" [value]="total"/>
</mat-form-field>

Upvotes: 1

Related Questions