.reset()清除表单,但不删除验证

时间:2018-09-17 12:26:40

标签: angular angular-reactive-forms

我有一个反应式表单,其中有一个密码字段,提交表单后,我想重置该表单。从谷歌搜索和阅读文档来看,.reset()应该将所有值都设置为null,并使所有内容pristineuntouched都变为零。但是,当我按下reset键时,我的类上仍然有ng-touchedng-invalid类。我不确定哪里可能出问题了?用的最简单的形式是:

<form [formGroup]="newPassForm" (submit)="submitNewPass()">
    <div class="row">
        <mat-form-field>
            <mat-label>Password:</mat-label>
            <input matInput type="password" formControlName="currentPass">
        </mat-form-field>
        <div *ngIf="invalidPass" class="notice notice-error">Wrong password</div>
    </div>
    <div class="row">
        <button mat-raised-button color="primary">Submit</button>
    </div>
</form>

我的控制器为

ngOnInit() {
    this.newPassForm = this.formBuilder.group({
        currentPass: [
            '',
            [Validators.required, Validators.minLength(8)]
        ],
    });
}

submitNewPass() {
    this.newPassForm.reset({ currentPass: '', newPass: '' });
    return;
}

我也尝试过删除材料,但没有任何效果。

1 个答案:

答案 0 :(得分:0)

尝试:

<form [formGroup]="newPassForm" #f="ngForm">
  ...
</form>

ts:

@ViewChild('f') myNgForm;

submitNewPass() {
    this.myNgForm.resetForm({ currentPass: '', newPass: '' });
}

DEMO