web-dev-qa-db-ja.com

どうすればリセットできますAngular Reactive Form

angularフォームをリセットする方法を見つけようとして失敗しました。

誰か助けてもらえますか?

<form #thisIsAForm>
  <mat-form-field class="full-width">
    <input matInput placeholder="Weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>

export class Example{
  @ViewChild('thisIsAForm') thisIsAForm;

  resetForm() {
    this.thisIsAForm.reset();
  }
}
7
physicsboy

ほとんど !そのためにリアクティブフォームを使用します。

<form [formGroup]="myForm">
  <mat-form-field class="full-width">
    <input matInput placeholder="Weather" formControlName="weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="myForm.reset()">Reset</button>


export class Example{
  myForm: FormGroup;

  constructor(private fb: FormBuilder) { 
    this.myForm = fb.group({
      weather: ''
    });
  }

  // If the HTML code doesn't work, simply call this function
  reset() {
    this.myForm.reset();
  }
}
19
user4676340
<form [formGroup]="thisIsAForm" (ngSubmit)="onSubmit()">
  <mat-form-field class="full-width">
    <input formControlName="weather" placeholder="Weather">
  </mat-form-field>
</form>
<button mat-raised-button (click)="resetForm()">Reset</button>


export class Example{
  thisIsAForm: FormGroup;

  constructor() {
    this.thisIsAForm = new FormGroup(
      weather: new FormControl('')
    ); 
  }

  resetForm() {
    this.thisIsAForm.reset();
  }
}
2
axl-code

ここでは、フォームをダーティにすることなくテンプレート駆動フォームをリセットしています。

    <form class="example-form" #charreplaceform="ngForm">
          <mat-form-field class="example-full-width">
            <input matInput #codepointSel="ngModel" (change)="createReplacementChar()" (keyup)="checkForNumber()"
              required [(ngModel)]="charReplaceInfo.codePoint" name="code-point" placeholder="Code Point (Only number)"
              [disabled]="isDisabled">
          </mat-form-field>

          <a (click)="refreshCharRecord(charreplaceform)">
            <i class="material-icons">
              loop
            </i>
          </a>
    </form>

    // in .ts
    refreshCharRecord(form: NgForm) { // getting the form reference from template 
    form.form.reset();   // here we are resetting the form without making form dirty
  }
0
Shreesh Mishra

In Angular 8

_<form #form="ngForm" (ngSubmit)="process(form)">

process(form: NgForm) { ...
_

_--prod_でビルドすると、次のエラーが表示されます

タイプ 'FormGroupDirective'の引数は、タイプ 'NgForm'のパラメーターに割り当てることができません。

_(ngSubmit)_に

私がしたことは、formテンプレート参照をFormGroupDirectiveとして挿入し、resetForm()を呼び出すことでした。

_<form #form (ngSubmit)="process(form)">

@ViewChild('form', { static: false }) FormGroupDirective formDirective;
_

FormGroupDirective を参照してください

0
Chuk Lee