最小限の Stackblitz の例
https://stackblitz.com/edit/angular-mqqvz1
Angular 7 アプリで、フィールドを持つ単純なコンポーネントを作成しました<input>
。
キーボードで入力値を変更するときは、値をonBlurにフォーマットします。- 最小限の例では、文字列「EDIT」を追加したいだけです。
これは基本的に機能しています:
- 「test」と入力してフィールドをぼかすと、「test EDIT」に変更されます
- 「lala」と入力してフィールドをぼかすと、「lala EDIT」に変更されます
ただし 、「テスト」と入力すると、ぼかし(機能します)、「テスト」と再度入力すると、機能しなくなります。
関数が呼び出され(onInputUpdate()
コンソール ログで確認できます)、変数inputValue
が更新されます (コンポーネントで確認できます{{inputValue}}
)。ただし、入力値は変更されません。
「test EDIT」になると思いますが、「test」のままです。
別の文字列を入力すると機能しますが、同じ文字列を 2 回続けて入力すると機能しません。何故ですか?どうすればこれを修正できますか?
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)
}
}