Sarah Sarena
Sarah Sarena

Reputation: 89

Disable validation on selection of radio button in angular

I have a form with 3 fields: type(radio button), name and place. If I select value 'Y' from radio button validations should appear for name and place. If I select value 'N' from radio button validation should not show for place. Please help me achieve the functionality. Working stackblitz: https://stackblitz.com/edit/angular-ivy-jzjh4j?file=src%2Fapp%2Fapp.component.ts

<input type="radio" formControlName="type" name="type" value="Y"/>
Yes
  <input type="radio" (change)="onChange($event)"
  formControlName="type" name="type" value="N"/>
No

  <small class="errormessage" *ngIf="submitted && addForm.controls.type.hasError('required')">
                            type is required
  </small>

TS

  onChange(evt)
  {
  var target = evt.target;
      if (target.checked) 
      {
        alert('hi');
        this.addForm.controls.place.valid === true;
      }
      else
      {
        this.addForm.controls.place.valid === false;
      }
}

Upvotes: 1

Views: 1878

Answers (1)

Random
Random

Reputation: 3236

Actually, you should not mix reactiveForm with template forms. So if you use a fromGroup, do not use (change) on HTML inputs. You have to subscribe to changes in your typescript. Also, your place input is required only if Y type is selected. So if user selects N, you have to remove the required validator, so your form will be valid.

Here is your updated stackblitz:

  constructor(private formBuilder: FormBuilder) {}
  addForm: FormGroup;
  submitted = false;
  mySubscription: Subscription;

  ngOnInit(): void {
    this.addForm = this.formBuilder.group({
      type: ["", [Validators.required]],
      name: ["", [Validators.required]],
      place: ["", [Validators.required]]
    });
    this.mySubscription = this.addForm
                              .get('type')
                              .valueChanges
                              .subscribe(newValue => {
      if (newValue === 'N') {
        // place is not required anymore
        this.addForm.get('place').setValidators([]);
      } else {
        // place is required
        this.addForm.get('place').setValidators([Validators.required]);
      }
      // force valitators to be triggered, to update form validity.
      this.addForm.get('place').updateValueAndValidity();
    });
  }

  onSubmit() {
    this.submitted = true;
    if (this.addForm.invalid) {
      return;
    }

  }

  ngOnDestroy() {
    if (this.mySubscription) {
      this.mySubscription.unsubscribe();
    }
  }

Upvotes: 3

Related Questions