heliya rb
heliya rb

Reputation: 830

angular reactive form doesn't support ngIf

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

Upvotes: 0

Views: 4415

Answers (3)

Kamran Khatti
Kamran Khatti

Reputation: 4127

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

Upvotes: 6

ng-hobby
ng-hobby

Reputation: 2199

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.

Upvotes: 0

Nikolay
Nikolay

Reputation: 340

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

Upvotes: 0

Related Questions