angular 14 form says INVALID after patchvalue to form controls

92 views Asked by At

In my angular component I am using PatchValue to set the values after the component in loaded when 'Back' button is clicked from its page2child. I emit an event and listen to the event and using PatchValue. After the form is set with valid values, I see form status as INVALID and my 'Next button' is not enabled which takes to page2(child).

parent-component.html
<app-stepper #cdkStep [linear]="false">
    <cdk-step>
        <div>
                 <mat-form-field appearance="outline" >
                <mat-label >Legal Name</mat-label>
                <input type="text" formControlName="legalName" matInput>             
            </mat-form-field>
           
            <mat-form-field appearance="outline" >
                <mat-label >City </mat-label>
                <input type="text" formControlName="city" matInput>
            </mat-form-field>
            
                                <button mat-button type="button" [disabled]="form.invalid"
                                 (click)="next()">
                             
                                NEXT  
                            </button>
                            
        </div>  
   </cdk-step>
    <cdk-step [editable]="true" [optional]="true" label="Review and Submit">
        <form-step-child 
            (goBackStepEvent)="goBackStepEvent($event)">
        </app-quote-submission-step2>
    </cdk-step>
</app-stepper>

parent-component.ts

 goBackStepEvent(eventval:any){
  this.form.controls['legalName']?.
            patchValue(eventval.legalName);
  this.form.controls['city']?.
            patchValue(eventval.city);
    for (const name in controls) {
        if (controls[name].invalid) {
            console.log('iNVALID fields ', name);
            
        }
    }
 }

In the console, I see both form controls (legalname and city) which has values set in it. But the form value is INVALID. I tried using following lines, still says form in INVALID and NEXT button is not enabled.

this.form.controls['legalName']?.markAsUntouched(); this.form.controls['legalName']?.updateValueAndValidity(); this.form.controls['city']?.markAsUntouched(); this.form.controls['city']?.updateValueAndValidity();

0

There are 0 answers