https://stackblitz.com/edit/angular-mqqvz1
In an Angular 7 App, I have created a simple component with an <input>
field.
When I change the input-value with the keyboard, I want the value to be formated onBlur. - In the minimal example I just want to add the string " EDIT" to it.
This is basically working:
However When I type in "test" - blur (it works) and type in "test" again, it does not work anymore!
The onInputUpdate()
-function gets called (You can see it in the console log), the variable inputValue
gets updated (You can see it in the component {{inputValue}}
), However the input-value does not change!
I expect it to be "test EDIT", however it stays "test".
When I type another string it works, however typing in the same string 2 times in a row does not work. Why is that? How can I fix this?
component.html
{{inputValue}} <br />
<input type="text"
[ngModel]="inputValue"
(ngModelChange)="onInputUpdate($event)"
[ngModelOptions]="{ updateOn: 'blur' }"/>
component.ts
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
inputValue = "teststring";
constructor(
private changeDetectorRef: ChangeDetectorRef,
) {}
public ngOnInit() {
this.inputValue = "initial";
}
public onInputUpdate(inputValue: string) {
this.inputValue = inputValue + ' EDIT';
this.changeDetectorRef.markForCheck();
console.log('onInputUpdate new inputValue', this.inputValue)
}
}
To make sure that the input field is updated after typing the same value again, force the view to update first with the raw text by calling ChangeDetectorRef.detectChanges
:
public onInputUpdate(inputValue: string) {
this.inputValue = inputValue; // Set value to raw input text
this.changeDetectorRef.detectChanges(); // Trigger change detection
this.inputValue = inputValue + ' EDIT';
this.changeDetectorRef.markForCheck();
}
See this stackblitz for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With