【问题标题】:Angular: Reinitialize reactive form materialAngular:重新初始化反应形式材料
【发布时间】:2021-09-28 00:42:43
【问题描述】:

我在使用来自材料库的一个输入的表单时遇到问题。

当我提交表单时,我在提交方法中这样重置它:

onSubmitPriceForm() {
      // to do......
      this.priceForm.reset();
    }

}

问题是表单在验证后显示如下:

我希望该字段恢复到照片 1 中的原始状态

我该怎么做?

谢谢!

在这里编辑验证器:

initPriceForm() {
    this.priceForm = this.formBuilder.group({
      price: ['', [Validators.required, Validators.pattern(this.pricePattern)]]
    });
  }

新编辑:这是 html 表单:

<form [formGroup]="priceForm" (ngSubmit)="onSubmitPriceForm()">
            <div class="edit-price-form">
                <mat-form-field appearance="outline" errorState="false">
                    <mat-label>{{ 'PRIX_TTC.NOUVEAU_PRIX_TTC' | translate }}</mat-label>
                    <input matInput name="price" autocomplete="off" formControlName="price" required>
                </mat-form-field>
    
                <button type="button" mat-mini-fab color="primary">
                    <mat-icon>done</mat-icon>
                </button>
            </div>
        </form>

【问题讨论】:

  • 很难说没有看到您的验证器实现,但通常您需要将您的 FormGroup / FormControls 标记为未触及和/或原始,即this.priceForm.markAsPristine(); this.priceForm.markAsUntouched();
  • 我添加了验证器,谢谢

标签: angular angular-material angular-reactive-forms mat-form-field


【解决方案1】:

默认情况下,当控件无效时会显示这些错误消息 并且用户已经与元素交互(触摸)或 父表单已提交

您可以使用 customError 匹配器更改此行为

component.ts

export class InputOverviewExample {
  matcher = new MyErrorStateMatcher();
  group = new FormGroup({
    control:new FormControl('', Validators.required)
  })
}

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    // const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched));
  }
}

component.html

<form #form="ngForm" [formGroup]="group" class="example-form">
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>Favorite food</mat-label>
    <input [errorStateMatcher]="matcher" matInput placeholder="Ex. Pizza" formControlName="control">
  </mat-form-field>

  <button (click)="group.get('control')!.reset();"> Click</button>
  
</form>

Working Example

【讨论】:

猜你喜欢
  • 2022-11-25
  • 2018-10-18
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2017-04-20
  • 2019-12-13
  • 2020-05-19
相关资源
最近更新 更多