1

My rather complex Stackblitz

Normally when I have complex validation in reactive forms I would define a formGroup for those controls that depend on each other.

This is not possible in the above senario, where we have 3 steps = 3 groups and the depending 3 fields firstUnique, secondUnique, thirdUnique.

<form [formGroup]="myForm">
<mat-horizontal-stepper formArrayName="formArray" #stepper>
  <mat-step formGroupName="0" [stepControl]="formArray?.get([0])" errorMessage="Name is required.">
      <ng-template matStepLabel>Fill out your name</ng-template>
      <mat-form-field>
        <input matInput placeholder="Last name, First name" formControlName="firstCtrl" required>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="UNIQUE1" formControlName="firstUnique" required>
      </mat-form-field>
      <div>
        <button mat-button matStepperNext>Next</button>
      </div>
  </mat-step>
  <mat-step formGroupName="1" [stepControl]="formArray?.get([1])" errorMessage="Address is required.">
      <ng-template matStepLabel>Fill out your address</ng-template>
      <mat-form-field>
        <input matInput placeholder="Address" formControlName="secondCtrl" required>
      </mat-form-field>
            <mat-form-field>
        <input matInput placeholder="UNIQUE2" formControlName="secondUnique" required>
      </mat-form-field>
      <div>
        <button mat-button matStepperPrevious>Back</button>
        <button mat-button matStepperNext>Next</button>
      </div>
  </mat-step>
  <mat-step formGroupName="2" [stepControl]="formArray?.get([2])" errorMessage="Error!"> 
    <ng-template matStepLabel>Done</ng-template>
    You are now done.
    <div>
      <mat-form-field>
        <input matInput placeholder="UNIQUE3" formControlName="thirdUnique" required>
      </mat-form-field>
      <button mat-button matStepperPrevious>Back</button>
      <button mat-button (click)="stepper.reset()">Reset</button>
    </div>
  </mat-step>

</mat-horizontal-stepper>

I use techniques described SO_answer and Material_docs

My Solution is working so far, but im not satisfied with it:

  1. On startup Unique Validation is run a thousand times (30-40 times) (hacky)
  2. On EVERY change of ANY input in the whole stepper the Unique Validation is trigger. (this is because I had to add it to the whole formGroup).
  3. A simple task as those 3 input field need to be UNIQUE has become a boilerplatey and complex mess. (please observe the function Unique(arr: string[]))

  4. When a correct step gets invalid by the UNIQUE Validator or the STEP gets valid again the STEPPER-VALIDATION is not invoked. (example: firstUnique = "a", secondUnique "b", thirdUnique = "a" (again) )

MyForm

this.myForm = this._formBuilder.group({
  formArray:
  this._formBuilder.array([
    this._formBuilder.group({
        firstCtrl: [''],
        firstUnique: [''],
    }),
    this._formBuilder.group({
        secondCtrl: [''],
        secondUnique: [''],
    }),
     this._formBuilder.group({
        thirdUnique: [''],
    })
  ])

}, {
  validator: [Unique(['0;firstUnique', '1;secondUnique', '2;thirdUnique'])]
});

Unique Validator fun

function Unique(arr: string[]) {

const validKey = "uniqueValid";

return (formGroup: FormGroup) => {

    const myValues =
    arr.map(path => {
      const s = path.split(';');
      return (<FormArray>formGroup.get('formArray'))
      .controls[parseInt(s[0])]
      .controls[s[1]];
    });

    const myKeys = arr.map(path => path.split(';')[1] )

    const obj = {};

    myKeys.forEach(function (k, i) {
      obj[k] = myValues[i];
    })

    myKeys.forEach((item, index) => {
      debugger
      console.log('unique validation function runs')

      const control = obj[item];

      const tmp = myKeys.slice();
      tmp.splice(index,1);

      const ans = tmp
      .filter( el => obj[item].value === obj[el].value)

      if ( ans.length && control.value ) {
        const err = {}
        err[validKey] = `identicial to: ${ans.join(', ')}`
        control.setErrors(err);
      } else if ( obj[item].errors && !obj[item].errors[validKey] ) {
        return; 
      } else {
        control.setErrors(null);
      }

    })
}
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69

1 Answers1

3

Using ngx-sub-form library, here's a live demo on Stackblitz:

https://stackblitz.com/edit/ngx-sub-form-stepper-form-demo

To explain a bit, it'd look like the following:

First, we need to define some interfaces so that our code can be robust and type safe

stepper-form.interface.ts

export interface Part1 {
  firstCtrl: string;
  firstUnique: string;
}

export interface Part2 {
  secondCtrl: string;
  secondUnique: string;
}

export interface Part3 {
  thirdUnique: string;
}

export interface StepperForm {
  part1: Part1;
  part2: Part2;
  part3: Part3;
}

From the top level component, we don't even want to be aware that there's a form. We just want to be warned when there's a new value saved.

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public stepperFormUpdated(stepperForm: StepperForm): void {
    console.log(stepperForm);
  }
}

app.component.html

<app-stepper-form (stepperFormUpdated)="stepperFormUpdated($event)"></app-stepper-form>

Now we start using the library and create the top level form (root) and expose the result as an output. We also define the constraint that the 3 unique inputs shouldn't have the same values.

stepper-form.component.ts

@Component({
  selector: 'app-stepper-form',
  templateUrl: './stepper-form.component.html',
  styleUrls: ['./stepper-form.component.css']
})
export class StepperFormComponent extends NgxRootFormComponent<StepperForm> {
  @DataInput()
  @Input('stepperForm')
  public dataInput: StepperForm | null | undefined;

  @Output('stepperFormUpdated')
  public dataOutput: EventEmitter<StepperForm> = new EventEmitter();

  public send() {
    this.manualSave();
  }

  protected getFormControls(): Controls<StepperForm> {
    return {
      part1: new FormControl(),
      part2: new FormControl(),
      part3: new FormControl(),
    }
  }

  public getFormGroupControlOptions(): FormGroupOptions<StepperForm> {
    return {
      validators: [
        formGroup => {
          if (!formGroup || !formGroup.value || !formGroup.value.part1 || !formGroup.value.part2 || !formGroup.value.part3) {
            return null;
          }

          const values: string[] = [
            formGroup.value.part1.firstUnique,
            formGroup.value.part2.secondUnique,
            formGroup.value.part3.thirdUnique,
          ].reduce((acc, curr) => !!curr ? [...acc, curr] : acc, []);

          const valuesSet: Set<string> = new Set(values);

          if (values.length !== valuesSet.size) {
            return {
              sameValues: true
            };
          }

          return null;
        },
      ],
    };
  }
}

Time to create our template using the utilities provided by the lib

stepper-form.component.html

<form [formGroup]="formGroup">
  <mat-horizontal-stepper>
    <mat-step>
      <ng-template matStepLabel>First control</ng-template>

      <app-first-part [formControlName]="formControlNames.part1"></app-first-part>

      <button mat-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>
      <ng-template matStepLabel>Second control</ng-template>

      <app-second-part [formControlName]="formControlNames.part2"></app-second-part>

      <button mat-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>
      <ng-template matStepLabel>Third control</ng-template>

      <app-third-part [formControlName]="formControlNames.part3"></app-third-part>

      <button mat-button (click)="send()">Send the form</button>
    </mat-step>
  </mat-horizontal-stepper>
</form>

<div *ngIf="formGroupErrors?.formGroup?.sameValues">
  Same values, please provide different ones
</div>

Now, let's create our first sub component

first-part.component.ts

@Component({
  selector: 'app-first-part',
  templateUrl: './first-part.component.html',
  styleUrls: ['./first-part.component.css'],
  providers: subformComponentProviders(FirstPartComponent)
})
export class FirstPartComponent extends NgxSubFormComponent<Part1> {
  protected getFormControls(): Controls<Part1> {
    return {
      firstCtrl: new FormControl(),
      firstUnique: new FormControl(),
    }
  }
}

and its template

first-part.component.html

<div [formGroup]="formGroup">
  <mat-form-field>
    <input matInput placeholder="First" type="text" [formControlName]="formControlNames.firstCtrl">
  </mat-form-field>

  <mat-form-field>
    <input matInput type="text" placeholder="First unique" [formControlName]="formControlNames.firstUnique">
  </mat-form-field>
</div>

Then pretty much the same for second-part.component.html and third-part.component.html so I'm skipping it here.

I've assumed that you did not really need a FormArray in that case and wasn't sure about the whole validation code that you had so I just built one that errors if at least 2 unique values are the same.

https://stackblitz.com/edit/ngx-sub-form-stepper-form-demo

Edit:

If you want to go further, I've just published a blog post to explain a lot of things about forms and ngx-sub-form here https://dev.to/maxime1992/building-scalable-robust-and-type-safe-forms-with-angular-3nf9

maxime1992
  • 22,502
  • 10
  • 80
  • 121
  • You solution adds the validation to the outerform which is nice. But I also want the Stepper Headers and Form Inputs to reflect the error for a full user experience. – Andre Elrico Jun 13 '19 at 07:45