Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular7 - [ngModel] does not update in component, when typing in the same value twice

Minimal Stackblitz Example

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:

  • If I type in "test" and blur the field, it will be changed to "test EDIT"
  • If I type in "lala" and blur the field, it will be changed to "lala EDIT"

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)
  }
}
like image 434
Michael B Avatar asked Jan 07 '19 22:01

Michael B


1 Answers

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.

like image 134
ConnorsFan Avatar answered Oct 19 '22 18:10

ConnorsFan