【问题标题】:Angular 6 form returns validation error after submit and resetAngular 6 表单在提交和重置后返回验证错误
【发布时间】:2018-08-25 05:04:59
【问题描述】:

我正在使用 Angular 6,我有一个表单和一个按钮。当我按下按钮时,应用程序会在表单上方显示表单数据,然后我调用form.reset()。但是在表单重置后,输入字段变为红色,因为我在表单中设置了所需的字段。哪里有问题?

app.html

<form [formGroup]='fuelForm'>
      <mat-form-field class="input input2">
        <input matInput placeholder="Nozzle name" formControlName="nozzleName">
      </mat-form-field>
      <mat-form-field class="input input2">
        <input matInput type="number" min="1" id="nozzleNumber" formControlName="nozzleNumber" placeholder="Nozzle number"  >
      </mat-form-field>
      <mat-form-field class="input input4">
        <mat-select placeholder="Fuel type" formControlName="fuelType">
          <mat-option *ngFor="let item of fuelList" [value]="item">{{item}}</mat-option>
        </mat-select>
      </mat-form-field>
      <button mat-icon-button class="circle_button" (click)="add()">
        <mat-icon class="plus_icon">add_circle_outline</mat-icon>
      </button>
    </form>

app.ts

export class DialogNozzleComponent {

fuelForm :FormGroup;

  fuelList = ['Petrol', 'Super petrol', 'Euro4 petrol', 'Gasoline', 'Euro4 gasoline'];
  nozzleItem = [
    {
      nozzleName: 'Nozzle',
      nozzleNumber: '1',
      fuelType: 'Super petrol'
    },
    {
      nozzleName: 'Nozzle',
      nozzleNumber: '2',
      fuelType: 'Gasoline'
    }
  ];

  constructor(public fb : FormBuilder) { 
    this.fuelForm = fb.group({
      nozzleName: {value:'Nozzle', disabled: true},
      nozzleNumber: [null, Validators.required],
      fuelType: [null, Validators.required]
    });
  }

  add() {
    const formValue = this.fuelForm.value;
    formValue.nozzleName = this.fuelForm.controls['nozzleName'].value;
    this.nozzleItem.push(formValue);
    this.fuelForm.controls['nozzleNumber'].reset();
    this.fuelForm.controls['fuelType'].reset();
  }
}

【问题讨论】:

    标签: javascript typescript angular6 angular-reactive-forms angular2-form-validation


    【解决方案1】:

    你试过了吗

    this.fuelForm.reset();
    this.fuelForm.markAsPristine();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-10
      • 2018-03-13
      • 1970-01-01
      • 2019-04-08
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      相关资源
      最近更新 更多