Angular Material 2 matHorizontalStepper form validation

此生再无相见时 提交于 2019-12-24 23:07:40

问题


I am using matHorizontalStepper from Angular Material 5.2.4 with Angular 4/5. Linear mode is on. On step 1 I have a form with two inputs which are required. But stepper checks if only one required input is filled. It's enough for stepper that user filled only one required field and let the user go for the step 2.

Here's what I'm talking about https://angular-ugvs4m.stackblitz.io

What can I set stepper to validate if all required inputs are filled ?


回答1:


I forked your stackblitz app and fixed your error. Live example

Your error was using the same control for the [stepControl], [formGroup] and for both inputs with formControlName (firstName and lastName).

You need to create a parent formGroup (firstFormGroup in your example), and then two FormControls inside it (firstName and lastName). The rest is just connecting it right in the html.

Also notice that I removed required from all the <input> elements. If you are using template driven forms, you do not need to put in on the html elements.

fixed component file

  ngOnInit() {
    this.firstFormGroup = this._formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required]
    });
    this.secondFormGroup = this._formBuilder.group({
      address: ['', Validators.required],
    });
  }

fixed html template

<mat-horizontal-stepper [linear]="true" #stepper="matHorizontalStepper">
  <mat-step [stepControl]="firstFormGroup">
    <form [formGroup]="firstFormGroup">
      <ng-template matStepLabel>Fill out your name</ng-template>
      <mat-form-field>
        <input matInput placeholder="First name"  formControlName="firstName">
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="Last name" formControlName="lastName" >
      </mat-form-field>
      <div>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>
  <mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>Fill out your address</ng-template>
      <mat-form-field>
        <input matInput placeholder="Address" formControlName="address" required>
      </mat-form-field>
      <div>
        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>
  <mat-step>
    <ng-template matStepLabel>Done</ng-template>
    You are now done.
    <div>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>
    </div>
  </mat-step>
</mat-horizontal-stepper>


来源:https://stackoverflow.com/questions/49479458/angular-material-2-mathorizontalstepper-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!