中安拓也のブログ

プログラミングについて書くブログ

【Angular】 送信後にフォームをリセットする

やりたいこと

フォームのSubmitに成功したら、フォームに入力した内容もバリデーションの状態もリセットしたい。

環境

  • Angular@7.2.0
  • Angular Material@7.3.7

コーディング

NgForm.resetForm()を使う。

FormGroup.reset()でもフォームのリセットができそうにみえるが、FormGroup.reset()だとフォームの値のみをリセットするため、必須バリデーションなどに引っかかってしまう。

f:id:l08084:20191110190334p:plain
FormGroup.reset()だと必須バリデーションに引っかかる

それでは、NgForm.resetForm()で送信後にバリデーションと値をリセットする処理を書いていく。

まず、テンプレート(HTML)から...

<form class="example-form" (ngSubmit)="onSubmit(createNgForm)" [formGroup]="createFormGroup" #createNgForm="ngForm">
  <!-- タイトル欄 -->
  <mat-form-field class="example-full-width">
    <input matInput class="title" placeholder="Title" formControlName="title" />
  </mat-form-field>

  <!-- 詳細欄 -->
  <mat-form-field class="example-full-width">
    <textarea matInput cdkTextareaAutosize cdkAutosizeMinRows="10" cdkAutosizeMaxRows="30" placeholder="Discription"
      formControlName="description"></textarea>
  </mat-form-field>
  <button type="submit" class="login-button" mat-raised-button [disabled]="false" color="primary">Save</button>
</form>

重要なのは、(ngSubmit)="onSubmit(createNgForm)" [formGroup]="createFormGroup" #createNgForm="ngForm"の部分となる。

#createNgForm="ngForm"でngFormの参照変数を定義した後、その参照変数を(ngSubmit)="onSubmit(createNgForm)"でsubmitイベントの処理に渡しています。

続いて、Submitイベントで呼び出されるメソッドについて

  public onSubmit(form: NgForm) {
    // スピナーを表示する
    this.spinnerService.show();

    // ログインしているユーザ情報の取得
    const user = this.afAuth.auth.currentUser;

    // メモを新規作成する
    this.memo = {
      id: '',
      title: this.titleControl.value,
      description: this.descriptionControl.value,
      createdUser: user.uid,
      createdDate: firebase.firestore.FieldValue.serverTimestamp(),
      updatedDate: firebase.firestore.FieldValue.serverTimestamp()
    };
    this.afStore
      .collection('memos')
      .add(this.memo)
      .then(docRef => {
        this.memoCollection.doc(docRef.id).update({
          id: docRef.id
        });
        // フォームをリセットする
        form.resetForm();
      })
      .finally(() => {
        // スピナーを非表示にする
        this.spinnerService.hide();
      });
  }

メソッドの引数として受け取っているform: NgFormを使って、フォームの保存処理が成功したタイミングでform.resetForm();を呼び出すことによって、フォームの内容とバリデーションのリセットを行なっています。

動作確認

実装が終わったので実際に動かしてみます。

フォームにテキストを入力してsubmitボタンを押下する。

f:id:l08084:20191110192323p:plain
submitボタンを押下すると...

保存処理が成功したタイミングでバリデーションもフォームへの入力内容もリセットされる。

f:id:l08084:20191110192536p:plain
フォームがリセットされている

参考サイト

angular - Cleanest way to reset forms - Stack Overflow

【2021/1/15 追記】

Angular Materialを使用していない場合は、NgForm.resetForm()でもバリデーションエラーをリセットできないとの指摘をいただきました。