【问题标题】:How to reset a form after component leave in angular 7组件离开角度7后如何重置表单
【发布时间】:2019-11-10 00:25:03
【问题描述】:

我正在处理 Angular 7 中的反应式表单。我有 3 个组件,每个组件都有一个表单。基于 if,组件切换。我没有使用路由,只是隐藏和显示组件。如果我们返回到前一个组件。然后角度材料输入有一个红色边框。如何删除该边框

dashboard.component.ts(父)

<section>
  <mat-card class="auth-card">

    <mat-card-content>
      <div [ngStyle]="componentConst.showAcc ? {'display':'block'} : {'display':'none'}" id="acc ">
        <app-account (showStep)="onNextStepShow($event)"></app-account>
      </div>
      <div [ngStyle]="componentConst.showC ? {'display':'block'} : {'display':'none'}" id="cred ">
        <app-cred (showNextStep)="onNext($event)" (showStip)="onShowPrev()"></app-cred>
      </div>

appaccount.ts


    <form [formGroup]="providerForm" (ngSubmit)="onSubmit()">
      <div class="form-control">
        <mat-form-field>
          <input  type="text" placeholder="Provider" matInput [matAutocomplete]="auto"
            formControlName="providerName">
          <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChanged($event)">
            <mat-option *ngFor="let providerItem of providersData" [value]="providerItem.providerName">
              {{providerItem.providerName}}</mat-option>
            <mat-option *ngIf="providersData.length===0  && isSearching!='false'" disabled>Begin typing to search...
            </mat-option>
          </mat-autocomplete>
          <mat-error *ngIf="submitted && formControl.providerName.errors">
            <mat-error *ngIf="formControl.providerName.errors.required"> * Provider is required</mat-error>
          </mat-error>
        </mat-form-field>
      </div>
      <div class="button-section">
        <button mat-button [disabled]="!isSelected">Next</button>
      </div>
    </form>

【问题讨论】:

  • 你有这方面的 stackblitz 吗?

标签: angular7 angular-reactive-forms


【解决方案1】:

在切换时间你应该重置一个表单。所以在那个时候重置但表单字段是触摸的,那么你会因为验证而得到一个红色边框。在表单事件之间的切换中加入这段代码。

this.providerForm.reset()
providerForm.markAsPristine();
providerForm.markAsUntouched();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 2021-07-29
    • 2019-09-02
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多