0
votes

I have a form group that I need to show one of the required inputs whit ngIf. but even when this input does not exist, formcontrol check it and return form is not valid. my code is like this html:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <label>mobile</label>
  <input type="text" formControlName="mobile" />

  <div *ngIf="!hasInfo">
    <label>firstName</label>
    <input type="text" formControlName="firstName" />
    <label>lastName</label>
    <input type="text" formControlName="lastName" />
  </div>
  <button type="submit">Submit</button>
</form>

ts:

constructor(){
 this.formBuilder();
}

ngOnInit() {
    if (accountResponse.length > 0) this.hasInfo= true;
}

formBuilder() {
    this.myForm= new FormGroup({
      mobile: new FormControl(null, Validator.required()),
      firstName: new FormControl(null, Validator.required()),
      lastName: new FormControl(null, Validator.required()),
    });
 }

onSubmit(){
  if(this.myForm.valid){
    console.log("valid")
  }else{
    console.log("not valid")
  }
}

if hasInfo is true that not to show firstName and lastName, my form should return valid but is always not valid

3
The form model is abstract, and required means required. You want it to be conditionally required, so you need a custom validator that implements this condition.Ingo Bürk
when you declare a form field in the component Angular is looking for it it the template. so it won't be enough to use *ngIf on the template only. I would choose a different approach here and try to programmatically add or remove a controluser12163165
I checked my form by custom condition and it's work, thank's for your help @Ingo Bürkheliya Rahbar

3 Answers

4
votes

You can add conditional validators on form initialization.

ngOnInit() {
  if (accountResponse.length > 0) this.hasInfo= true;
  this.formBuilder();
}

formBuilder() {
  const required = this.hasInfo ? Validator.required : null;

  this.myForm= new FormGroup({
    mobile: new FormControl(null, Validator.required),
    firstName: new FormControl(null, required),
    lastName: new FormControl(null, required),
  });
}
0
votes

You have to add/remove required validators from the FormControls when hasInfo is changed

Check this article - Dynamically Add/Remove Validators in Angular Reactive Forms

0
votes

ngIf just prevents rendering your div in the html file and it does not change your reactive form validation on your .ts file. for your purpose try this:

.ts:

ngOnInit() {
    if (accountResponse.length > 0) { 
      this.hasInfo= true;
      updateValidations();
    }
}

updateValidations() {
 if( this.hasInfo ) {
  this.myForm.get("firstName").clearValidators();
  this.myForm.get("firstName").updateValueAndValidity();
  this.myForm.get("lastName").clearValidators();
  this.myForm.get("lastName").updateValueAndValidity();
 }
}

based on the this.hasInfo changes, call this updateValidations function.