Angular - Requiring a checkbox to be checked

 


Component:
import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms';
public profileForm!: FormGroup;
constructor(
    private _fb: FormBuilder
  ) { }
ngOnInit(): void {
    this._createForm();
    this._setValidationRule();
}
get fc(): { [key: string]: AbstractControl } {
    return this.profileForm.controls;
  }
  private _createForm() {
    const self = this;
    self.profileForm = self._fb.group({
      required_checkbox: [false],
      zipcode: [''],
      city: [''],
      town: [''],
    });
  }
  private _setValidationRule() {
    const self = this;
    self.profileForm.get('required_checkbox').valueChanges.subscribe(
      ruleStatus => {
        if (ruleStatus) {
          self.profileForm.get('zipcode').setValidators(Validators.required);
          self.profileForm.get('city').setValidators(Validators.required);
          self.profileForm.get('town').setValidators(Validators.required);
        } else {
          self.profileForm.get('zipcode').setValidators(null);
          self.profileForm.get('city').setValidators(null);
          self.profileForm.get('town').setValidators(null);
        }
        self.profileForm.get('zipcode').updateValueAndValidity();
        self.profileForm.get('city').updateValueAndValidity();
        self.profileForm.get('town').updateValueAndValidity();
      });
  }
Template:
<mat-checkbox class="terms" formControlName="required_checkbox">Pickup Riraku</mat-checkbox>
<mat-form-field appearance="outline">
    <mat-label>Zip Code</mat-label>
    <input matInput type="text" formControlName="zipcode" placeholder="">
</mat-form-field>
<mat-form-field appearance="outline">
    <mat-label>City</mat-label>
    <input matInput type="text" formControlName="city" placeholder="">
</mat-form-field>
<mat-form-field appearance="outline">
    <mat-label>Town</mat-label>
    <input matInput type="text" formControlName="town" placeholder="">
</mat-form-field>
Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment