5

最小限の 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)
  }
}
4

1 に答える 1

5

同じ値を再度入力した後に入力フィールドが確実に更新されるようにするには、次のように呼び出して、最初に生のテキストでビューを強制的に更新します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();
}

デモについては、このスタックブリッツを参照してください。

于 2019-01-07T22:20:24.393 に答える