I have used allOf validator of @rxweb/reactive-form-validators in my project. This validator is used in the situation where user have to select atleast all of the mentioned checkboxes. It can be used directly in the component without creating any custom validation function.
You just have to mention RxwebValidators.allOf validator in your ts file while creating formGroup like this:
ngOnInit() {
this.employeeInfoFormGroup = this.formBuilder.group({
department:[''],
projectDomains:['', RxwebValidators.allOf({matchValues:["ECommerce", "Banking","Educational","Gaming"]})],
});
}
You can set the errorMessage in ReactiveFormConfig in your app.component.ts like this:
ReactiveFormConfig.set({"validationMessage":{"allOf":"You must select all options"}});
Here is the complete HTML:
<div>
<form [formGroup]="employeeInfoFormGroup">
<div class="form-group">
<label>Project Domains</label>
<div class="form-check" *ngFor="let tag of projectDomainsArray; let i = index;">
<h4>
<input (click)="addProjectDomain($event.target,i)" type="checkbox" value="{{tag}}" /> {{tag}}
</h4>
</div>
<br>
<small class="form-text text-muted">You must select atleast all option provided in the config parameters.</small><br>
<small class="form-text text-danger" *ngIf="employeeInfoFormGroup.controls.projectDomains.errors">{{employeeInfoFormGroup.controls.projectDomains.errors.allOf.message}}</small><br>
</div>
<button [disabled]="!employeeInfoFormGroup.valid" class="btn btn-primary">Submit</button>
</form>
</div>
Here is the complete component:
import { Component, OnInit } from '@angular/core';
import { FormGroup } from "@angular/forms"
import { RxFormBuilder, RxwebValidators } from '@rxweb/reactive-form-validators';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-allOf-add-validator',
templateUrl: './all-of-add.component.html'
})
export class AllOfAddValidatorComponent implements OnInit {
employeeInfoFormGroup: FormGroup
projectDomains: string[] = [];
projectDomainsArray: string[] = ["ECommerce", "Banking", "Educational", "Gaming"];
constructor(
private formBuilder: RxFormBuilder, private http: HttpClient) { }
ngOnInit() {
this.employeeInfoFormGroup = this.formBuilder.group({
department: [''],
projectDomains: ['', RxwebValidators.allOf({ matchValues: ["ECommerce", "Banking", "Educational", "Gaming"] })],
});
}
addProjectDomain(element: any, index: number) {
var indexOf = this.projectDomains.indexOf(element.value);
element.checked ? this.projectDomains.push(element.value) : this.projectDomains.splice(indexOf, 1);
this.employeeInfoFormGroup.controls.projectDomains.setValue(this.projectDomains);
}
}
Working example of allOf validator