Reputation: 1087
I try to modify the text from the input to clear all letters 'a'. With ngModelChange, the model has been changed, but the value in the input would not until I type another valid letter.
I can use something with view child likes input.value = this.testStr
after update model, but I wonder why the value in the input does not follow the model and if any better ways to deal with that.
Follow the topic at (ngModelChange) does not update the UI for specific input, I can change from using ngModelChange
to (change)
event, but that only work the input blurs. I want to change the input value immediately after typing. I tried with ChangeDetectorRef
after updating this.testStr
but it doesn't work also.
Upvotes: 2
Views: 5290
Reputation: 57919
you need also change the "value" of the input
<!--see that pass the input using a template reference variable-->
<input #input [ngModel]="testStr"
(ngModelChange)="validateInput($event,input)">
validateInput(e: any, input: any = null) {
const text = e.replace(/a/g, '');
this.testStr = text;
if (input.value != text) {
const start = input.selectionStart - 1;
input.value = text;
input.selectionStart = input.selectionEnd = start;
}
}
NOTE: It's necessary get the selectionStart if you type in the middle of the input.
See the stackblitz
NOTE2: please, don't attach image with code in an answer, it's better you write the code (after write code you select it and use Ctrl+K to formatter). It's makes more easy respond your question
Upvotes: 4