1

I am trying to add a condition to my form. Basically I only want to set some fields to mandatory if a checkbox is ticked. Here is my code.

  onCreateContactDetailsForm() {
    this.contactDetailsForm = new FormGroup({
      firstName: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
      mobileNumber: new FormControl(null, [Validators.required, Validators.pattern('^([0|\+[0-9]{1,5})?([1-9][0-9]{8}|[1-9][0-9]{9})$')]),
      surname: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
      workEmail: new FormControl(null, [Validators.email]),
      identityValue: new FormControl('', [Validators.required]),
      personalEmail: new FormControl(null, [Validators.email]),
      exitDate: new FormControl('', [Validators.required]),
      exitNoticeDate: new FormControl('', [Validators.required]),
      amount: new FormControl('', [Validators.pattern('^$|^[0-9]*$')]),
      dateOfBirth: new FormControl('', [Validators.required]),
      indebtedToEmployer: new FormControl(false),
      isHrEmailAddress: new FormControl(false),
      if(isHrEmailAddress) {
        address1: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
        address2: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
        address3: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
        postalCode: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
        postalCountry: new FormControl(null, [Validators.required, Validators.pattern('^[a-zA-Z\- ]*$')]),
      }
    });
  }

The if statement can't seem to be put here as it gives this error in my editor Type '(isHrEmailAddress: any) => void' is missing the following properties from type 'AbstractControl': validator, asyncValidator, _parent, _asyncValidationSubscription, and 44 more.

Is there any easier way to do this?

2 Answers 2

0

Angular FormGroup API has addControl method, we can use that to add FormControl dynamically.

Use isHrEmailAddress control valueChanges method listen whether the isHrEmailAddress checkbox is checked or not.

component.ts

constructor() {
    this.onCreateContactDetailsForm();
     this.addControls(this.isHrEmailAddressControl.value);
    this.isHrEmailAddressControl.valueChanges.subscribe(isHrEmailAddress => {
      this.addControls(isHrEmailAddress);
    });
  }

  addControls(isHrEmailAddress) {
    const controls = {
      address1: new FormControl(null, [
        Validators.required,
        Validators.pattern("^[a-zA-Z- ]*$")
      ]),
      address2: new FormControl(null, [
        Validators.required,
        Validators.pattern("^[a-zA-Z- ]*$")
      ]),
      address3: new FormControl(null, [
        Validators.required,
        Validators.pattern("^[a-zA-Z- ]*$")
      ]),
      postalCode: new FormControl(null, [
        Validators.required,
        Validators.pattern("^[a-zA-Z- ]*$")
      ]),
      postalCountry: new FormControl(null, [
        Validators.required,
        Validators.pattern("^[a-zA-Z- ]*$")
      ])
    };
    if (isHrEmailAddress) {
      Object.keys(controls).forEach(key => {
        this.contactDetailsForm.addControl(key, controls[key]);
      });
    } else {
      Object.keys(controls).forEach(key => {
        this.contactDetailsForm.removeControl(key);
      });
    }
  }

component.html

<form [formGroup]="contactDetailsForm">
    <input type="text" formControlName="firstName">
    <hr>
    <input type="checkbox" formControlName="isHrEmailAddress">
    <hr>
    <div *ngIf="isHrEmailAddressControl.value">
        <input type="text" formControlName="address1">
  </div>
</form>

Example

0

A possible way to do this is by adding a custom validator to your form controls, like this one:

Method 1

    let myRequiredValidator = (input: FormControl) =>{
        if(this.contactDetailsForm.getRawValue().isHrEmailAddress){
            const fieldInput = input.value;
            return fieldInput && fieldInput != "" ? null : { isRequiredAndEmpty: true };
        }
        return null;
    }

And then adding it to your validator array like this:

[myRequiredValidator, Validators.pattern('^[a-zA-Z\- ]*$')]

That would check for the value you're trying to condition, and let it pass or fail.

But there is another way to do this by adding and removing controls to the FormGroup

Method 2

When you get your value changed, you may run this to add the controls to the group:

this.contactDetailsForm.addControl('new', new FormControl('', Validators.required));

You may do this for every control you need, just replace 'new' with the desired name. And you may reverse that by running this:

this.contactDetailsForm.removeControl('new', null);

With that, your optional control will be removed from the group. You may this add/remove as you need.

Here's the FormGroup's documentation if something shows up. I hope that's helpful enough.

4
  • When I try method 1 I get this error ERROR TypeError: Cannot read property 'getRawValue' of undefined
    – skydev
    Jun 18, 2020 at 5:54
  • Perhaps, the scope of this was lost. Let _this equals to this outside the function and replace in-function this to _this and try. Jun 18, 2020 at 5:57
  • still gives the error. I tried method 2 and it seems to ignore the addcontrol too
    – skydev
    Jun 18, 2020 at 6:14
  • Please provide the changes you made so i can check :) Jun 18, 2020 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.