How to validate form builder while editing it when it has pre-filled values?

204 Views Asked by At

I am using angular 4 Form and Form-Group component to create a add/edit data form. I am able to proper validation at adding any new data but having problem while editing the same form with already filled input fields.

Below code is of Component part:

  this.saveNotification = this.formBuilder.group({
  id: '',
  name: ['', Validators.required],
  question: ['', Validators.required],
  repeatTypesControl: ['', Validators.required],
  remindAt: '',
});

if(this.isUpdateCheck){///pre-filled form on Edit
  this.saveNotification.patchValue({
    id: 4,
    name: "Deck", 
    question: "Who's Deck is this?",
    remindAt: "08:30pm",
  });

this.saveNotification.updateValueAndValidity();
   for (var i in this.saveNotification.controls) {
    this.saveNotification.controls[i].markAsTouched();
  }

Below code is of template part:

<button ion-button color="secondary" type="submit" [disabled]="(!saveNotification.valid)" color="dark">SAVE</button>

I am always getting saveNotification.valid value as false because at editing the values are getting per-filled from component. I tried this.saveNotification.controls[i].markAsTouched() but this doesn't worked.

1

There are 1 best solutions below

1
On

Insed of

this.saveNotification.patchValue({
   id: 4,
   name: "Deck", 
   question: "Who's Deck is this?",
   remindAt: "08:30pm"
});

Use

this.saveNotification.controls['id'].setValue(4);
this.saveNotification.controls['name'].setValue('Deck');
this.saveNotification.controls['question'].setValue('Who's Deck is this?');
this.saveNotification.controls['remindAt'].setValue('08:30pm');