The responsibility of validating the entire FormGroup
ideally falls on a Custom Validator that you can create. This validator will ensure that all fields within the FormGroup
are validated as a whole:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray } from "@angular/forms";
import { FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
myForm: FormGroup;
constructor(private readonly fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
uName: [''],
username: [''],
description: ['']
}, { validators: anyOneFieldRequired });
}
submit(value) {
console.log('Form Value: ', value);
}
}
function anyOneFieldRequired(formGroup: FormGroup) {
const uName = formGroup.controls['uName'].value;
const username = formGroup.controls['username'].value;
const description = formGroup.controls['description'].value;
return uName === '' && username === '' && description === '' ? { oneFieldRequired: true } : null;
}
In your template:
<form [formGroup]="myForm" (ngSubmit)="submit(myForm.value)">
<mat-form-field class="full-width">
<input matInput type="text" formControlName="uName">
</mat-form-field>
<mat-form-field class="full-width">
<input matInput type="text" formControlName="username" >
</mat-form-field>
<mat-form-field class="full-width">
<input matInput type="text" formControlName="description">
</mat-form-field>
<button mat-raised-button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
Check out this Sample StackBlitz for reference.