Home > Software design >  How validate a Reactive Form in Angular 10 using two groups inside my formBuilder.group
How validate a Reactive Form in Angular 10 using two groups inside my formBuilder.group

Time:09-16

I need to validate my form with two diferents groups inside the main formBuilder.group. I don't know how get the value 'errors' is my HTML [ngClass].

component.ts:

    creatFrom(): void {
    this.myForm = this.formBuilder.group({
      estimated: this.formBuilder.group({
        fieldDiff1: ['', Validators.required],
        fieldDiff2: ['', Validators.required],
        fieldDuration: [''],
        opDuration: ['', Validators.required],
        taxiInParameter: [''],
      }),
      realized: this.formBuilder.group({
        fieldDiff1: ['', Validators.required],
        fieldDiff2: ['', Validators.required],
        fieldDuration: [''],
        opDuration: [''],
        taxiInParameter: [''],
      }),
      taxiInParameter: ['', Validators.required],
    });
  }

component.html:

     <div formGroupName="estimated">
                    <div class="row">
                        <div class="form-group col-md-3" [ngClass]="{'has-error':mF.fieldDiff1.errors && isSubmited}">
                            <label class="control-label" for="estimated_fieldDiff1"><span translate>Data</span>1*:</label>
                            <ng-select 
                                id="estimated_fieldDiff1" name="estimated_fieldDiff1"
                                formControlName="fieldDiff1"
                                [items]="fieldsEstimatedData1"
                                class="select-option" required>
                            </ng-select>
                        </div>
                    </div>

CodePudding user response:

Please try below

[ngClass]="{'has-error':myForm.get('estimated').get('fieldDiff1').errors && isSubmited}"

Or

for better understanding in ts file

get estimateForm(): FormGroup {
   return this.get('estimated');
}

get realizedForm(): FormGroup {
   return this.get('realized');
}
[ngClass]="{'has-error':estimateForm.get('fieldDiff1').errors && isSubmited}"
  • Related