Home > Blockchain >  Angular reactive form validation error not working when using shared form in 2 child components
Angular reactive form validation error not working when using shared form in 2 child components

Time:12-08

I have a quick question

I am using the angular material reactive form in a service.ts file

form: FormGroup = this.fb.group({
  name: [,Validator.required],
  email: [,Validator.required],
})

and then I have a parent component and 2 child component something like this:

<parent>
<child1></child>
<child2></child>
</parent>

i am using formgroup in both the child1 and child2 component seperately by initializing service in the constructor, like this:

child1.component.ts

form: FormGroup = this.service.form;
constructor(service: myformService){}

child1.component.html

<form [formGroup]="form">
// input goes here
</form>

similarly in child2 component so, i have the same form getting called in 2 different component from service file.

I want to submit my form from the child2 component and show validation error, but validation error is not working. Can anyone please help me to solve this issue?

stackblitz: https://stackblitz.com/edit/user-registration-with-fgd-e7p9hb?file=src/app/user-registration/user-registration/user-registration.component.ts

Thanks,

Solution:

I want to show validation error in both the components (app-address, app-basic-info) when i click submit button

CodePudding user response:

You can use markAllAsTouched so that Angular Material will show the errors.

  onSubmit() {
    this.form.markAllAsTouched();
  }
<button type="submit" (click)="onSubmit()">Submit form</button>

Stackblitz: https://stackblitz.com/edit/user-registration-with-fgd-bpglg2?file=src/app/user-registration/user-registration/basic-info/basic-info.component.ts

CodePudding user response:

when the user click submits button, yes you can use this one:

this.form.markAllAsTouched();

however on the other hand, if you want to see it immediately could you use the below example.

<div
*ngIf="description?.invalid && (description?.dirty || description?.touched)"
<div *ngIf="description?.errors?.['minlength']">
  description must be at least 4 characters long.
</div>
<div *ngIf="description?.errors?.['maxlength']">
  description must be at least 100 characters long.
</div>
<div *ngIf="description?.errors?.['required']">
  description is required.
</div>
get description() {
    return this.myForm.get('description');
  }
  • Related