0

I have a form in Angular 9 which i want to validate based on a condition of a drop down box. In my case the form has a field massEmailType and that can have 2 values , either Farm or Contact. What i want is that if the User selects a Farm tractList is a required field.

  createForm(): FormGroup {
    return this.fb.group(
        {
            emailCampaign: [{value: '', disabled: false}, Validators.required],
            massEmailType: [{value: '', disabled: false}, Validators.required],
            tractList: ['', RxwebValidators.required({conditionalExpression: 'x => x.massEmailType === "Farm"' })],
            massEmailSender: [{value: '', disabled: false}, Validators.required],
       

        })
}

The initial validation works, so if the user selects Contact, it will validate without the value in tractList. But if the user changes his mind and gets back to Farm it still shows form as valid. Is there anything i need to do after it has been validated initial to make sure any changes will possibly invalidate form again ?

1 Answer 1

2

Use the rxjs to subscribe the changes of massEmailType control and verify the value and set the validator based on that value.

  ngOnInit(): void {

    const form = this.createForm()

    form.controls.massEmailType.valueChanges.subscribe((data) => {
      if (data === 'Farm') {
        form.controls.tractList.setValidators([Validators.required]);
      } else {
        form.controls.tractList.setValidators([]);
      }
    });
  }


  createForm(): FormGroup {
    return this.fb.group(
      {
        emailCampaign: [{ value: '', disabled: false }, Validators.required],
        massEmailType: [{ value: '', disabled: false }, Validators.required],
        tractList: [''],
        massEmailSender: [{ value: '', disabled: false }, Validators.required],
      });
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.