Santosh
Santosh

Reputation: 3837

Patch value not working after the first instance angular

I am trying to populate the form field when click on edit icon. For the first time it is working as expected but after I click different edit icon it doesn't update. Also if I hit cancel button and again click any edit button it is working fine. But it only works for the first time.

Stackblitz demo

I am calling that patchValue thing inside the ngAfterViewInit.

  ngAfterViewInit(): void {
     setTimeout(() => {
       this.editDataToForm();  
     }, );
  }

It should update the form field whenever I click any of the edit icon.

Upvotes: 1

Views: 1249

Answers (1)

Z. Bagley
Z. Bagley

Reputation: 9270

The issue is that the ngAfterViewInit lifecycle hook only is proc'd once during the component's life (after the view is initialized), and the component isn't being destroyed except for when you completely close the form.

In order to update the form any time the form data is changed you will also need to hook into the ngOnChanges lifecycle hook.

  ngOnChanges(changes: SimpleChanges) {
    console.log('change detected: ', changes)
    setTimeout(() => {
      this.editDataToForm();  
    }, );
  }

Forked StackBlitz: https://stackblitz.com/edit/angular-t7jams

Upvotes: 1

Related Questions