I have two buttons in the parent template. One button acts as the Submit for the parent/child form. The other should validate the child component form. Clicking the Submit button validates both - which is OK. However, I am not able to get the other button to validate my child component form. Essentially, show the required errors of Child form only when the "Check Phone" button is clicked.
Parent template:
<form id="sampleform" [formGroup]="sampleForm" (ngSubmit)="formsubmit()">
<mat-form-field>
<input matInput type="text" formControlName="name" [errorStateMatcher]="matcher">
<mat-error *ngIf="sampleForm.controls.name.hasError('required') && isShowErrors">This field is invalid</mat-error>
</mat-form-field>
<br/>
<br/>
<child-component [isShowErrors]="isShowErrors"></child-component>
</form>
<button type="button">Check phone</button> <br/>
<button type="submit" form="sampleForm" (click)="formsubmit()">Submit</button>
Parent Component TS:
export class AppComponent{
isShowErrors: boolean = false;
sampleForm: FormGroup;
matcher = new MyErrorStateMatcher();
constructor(private fb: FormBuilder){
}
ngOnInit(){
console.log(">>>>")
this.sampleForm = this.fb.group({
name: ['', Validators.required]
});
}
formsubmit(){
this.isShowErrors = true;
console.log(this.sampleForm);
if(this.sampleForm.valid){
//navigate
}
}
}
Child Component template:
<form [formGroup]="sampleChildForm">
<mat-form-field>
<input matInput type="text" formControlName="phone" [errorStateMatcher]="matcher">
<mat-error *ngIf="sampleChildForm.controls.phone.hasError('required') && isShowErrors">Test Error</mat-error>
</mat-form-field>
</form>
Stackblitz: https://stackblitz.com/edit/angular-gyzaag