Yasir
Yasir

Reputation: 1399

Form validation not working when reusing form

I have a form component where I used it for adding and editing. However there is a problem not sure how to address it

<button *ngIf="!editMode" ion-button type="submit" [disabled]="!experienceForm.valid" (click)="save(experienceForm)">
    Save
</button>
<button *ngIf="editMode" ion-button type="submit" [disabled]="!experienceForm.valid" (click)="update(experienceForm)">
    Update
</button>

the above code is self explanatory. Not forget to mention, if the form is for editing, I have populated the fields using ngModel so that the user can edit.

The update button shouldn't be disabled if the form is valid(meaning all fields currently valid)..but as far as I tested , this !experienceForm.valid is not working when the form is called for EDITING , if I replace it with any of attributes touch or dirty, like [disabled]="!experiencForm.dirty" then its working. but somehow valid does not trigger unless I re-input all the fields.

how to address this issue! Below I have provided a sample of all the code:

.ts:

constructor(...){
   this.userId = navParams.get('userId');    // get passed params
   this.userExp = navParams.get('userExperience'); // get passed params

   this.experienceForm = this.formBuilder.group({
      myInput1 : ['', Validators.required],
      myInput2: ['', Validators.required]
}
ionViewDidLoad(){
   if(this.userExp !== 'null'){        // if not null , then Its for editing
     this.editMode = true;
     this.myInputModel1 = this.userExp.value; // populating the fields
     this.myInputModel2 = this.userExp.value;
   }
}

.html: // !experience.valid does not trigger here for the button Update

<form [formGroup]="experienceForm" novalidate>
  <ion-item>
      <ion-label class="labels" floating>First</ion-label>
      <ion-input type="text" formControlName="myInput1" [(ngModel)]="myInputModel1"></ion-input>
    </ion-item>
   ///

  <button *ngIf="!editMode" ion-button type="submit" [disabled]="!experienceForm.valid" (click)="save(experienceForm)">
    Save
  </button>
  <button *ngIf="editMode" ion-button type="submit" [disabled]="!experienceForm.valid && !experienceForm.dirty" (click)="update(experienceForm)">
    Update
  </button>
</form>

Upvotes: 0

Views: 182

Answers (1)

sainu
sainu

Reputation: 2701

It is better to not use formControlName and ngModel together. You can assign form values as

ionViewDidLoad(){
   if(this.userExp !== 'null'){        // if not null , then Its for editing
     this.editMode = true;

    this.experienceForm = this.formBuilder.group({
      myInput1 : [this.userExp.value, Validators.required],
      myInput2: [this.userExp.value, Validators.required]
  });
}

I think this will solve your problem

Upvotes: 1

Related Questions