0
votes

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;
      }
}
1
do not manually set valid state... ! A control is valid if its validators are valid. If you want a field to not be in error, remove the validator which makes it in error. Can you show your addForm initialization ? - Random
Thank you for the response. Sir, onsubmit - I want to show validations for all fields. But when i select radio button as 'N' - I want to remove validation for "place". My working stackblitz sir - stackblitz.com/edit/… - Sarah Sarena

1 Answers

1
votes

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();
    }
  }