Reputation: 77
I'm having trouble binding input to a value in angular 4, for example [value]="inputFrom"
. Sometimes it changes when I change inputFrom, other times it doesn't. How do I make the input always change when inputFrom
change and not just sometimes?
Can you maybe suggest another way to accomplish what I'm trying to do?
Let me explain more about what I'm trying to do. I have two inputs:
<input [value]="inputFrom" type="number" [min]="inputMin" [max]="inputMax" (focusout)="onInputFromChanged($event.target.value)" />
<input [value]="inputTo" type="number" [min]="inputMin" [max]="inputMax" (focusout)="onInputToChanged($event.target.value)" />
I have inputMin
, inputMax
variables, that can be null. They indicate the min and max values for the range. If they're null, it means there's no min or max value.
I also have inputFrom
and inputTo
, which are binded to the html inputs.
I call onInputFromChanged
or onInputToChanged
functions when the input loses focus.
What I want to happen here is to validate the input value, and if it's not valid, fill it with a valid value.
What really happens is that the functions (onInputFromChanged
or onInputToChanged
) are called, then inputFrom
or inputTo
are changed, but in the browser, most of the time, the old value is left.
export class AppComponent {
inputMin = 100; // can be null
inputMax = 200; // can be null
inputFrom = 100;
inputTo = 200;
onInputFromChanged(valueStr: string): void {
const value = Number(valueStr);
if (this.inputMin != null && value < this.inputMin) {
this.inputFrom = this.inputMin;
}
}
onInputToChanged(valueStr: string): void {
const value = Number(valueStr);
if (this.inputMax != null && value > this.inputMax) {
this.inputTo = this.inputMax;
}
}
}
Other things I tried:
oninput="validity.valid||(value='');"
or onfocusout="validity.valid||(value='');"
to my input element. But what I need is to put inputMin
or inputMax
into the value, not an empty string.Upvotes: 0
Views: 1256
Reputation: 216
Try this
It works when there changes in input value.
export class AppComponent {
inputMin = 100;
inputMax = 200;
inputFrom = 100;
inputTo = 200;
handleInputChange(valueStr: string) {
const value = Number(valueStr);
if (this.inputMax != null && value > this.inputMax) {
this.inputTo = this.inputMax;
}
if (this.inputMin != null && value < this.inputMin) {
this.inputFrom = this.inputMin;
}
}
}
<input [ngModel]="inputFrom" type="number" [min]="inputMin" [max]="inputMax" (change)="handleInputChange($event.target.value)" (ngModelChange)="inputFrom = $event" />
<input [ngModel]="inputTo" type="number" [min]="inputMin" [max]="inputMax" (change)="handleInputChange($event.target.value)" (ngModelChange)="inputTo = $event"/>
Upvotes: 1