Reputation: 1684
I'm working on a scenario where I want the ngModel
to get update based on certain conditions
Template:
<mat-form-field>
<mat-label>val:</mat-label>
<input matInput [(ngModel)]="someVal" (ngModelChange)="onChange($event)">
</mat-form-field>
Component:
someVal: number = 10;
onChange(val: number):void {
if(val > 10){
this.someVal = 0;
}
}
On the first attempt to change the value to something greater than 10, the view updates. But subsequent changes don't. What causes this behavior and how does one work around this?
Upvotes: 0
Views: 619
Reputation: 1684
As a workaround I did this for now.
private _cdRef: ChangeDetectorRef
public someVal: number = 10;
onChange(val: number):void {
if(val > 10){
this.someVal = null;
this._cdRef.detectChanges();
this.someVal = 0;
}
}
Upvotes: 1
Reputation: 223
Add name property.
<input matInput name="val" [(ngModel)]="someVal" (ngModelChange)="onChange($event)">
Upvotes: 0
Reputation: 57231
Do not do this ...
[(ngModel)]="someVal" (ngModelChange)="onChange($event)"
do this ...
[ngModel]="someVal" (ngModelChange)="onChange($event)"
onChange(val: number):void {
if(val > 10) val = 0;
this.someVal = val;
}
Upvotes: 0