0

I have a formgroup which selects all the checkboxes user has selected and submits that on button click. But that button has to be disabled when no checkboxes are selected. It works on load, but as soon as user checks and unchecks the box it is still valid and doesnt update the statusChange of form. HTML Code:

<form [formGroup]="myform">
    <div *ngFor="let item of list$ | async">
        <input type="checkbox"> {{item.id}}<br>
    </div>
</form>
<button type="button" (click)="continue()" [disabled]="disableBtn$ | async" > Continue</button>

Angular Code:

this.myform = this.fb.group({
    listOfSelected: this.fb.array([], Validators.minLength(1))
});

this.myform.statusChanges
    .pipe(distinctUntilChanged())
    .subscribe((status: string) => console.log(status))

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I was looking for Angular FormBuilder
@Developer This can be used with Angular FormBuilder also. I have updated the stackblitz with Angular FormBuilder.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.