Fabian
Fabian

Reputation: 289

Updating data from modal in angular using ngx-bootstrap

I have an angular project that I am trying to update data using ng-bootstrap. I have the forms and installed the dependencies. Whenever I click on the edit button, the modal opens the edit form with the data populated. So far, this is what I wanted. However, whenever I change the value from modal, the table also changes and it reflects the data in the table in real time. What I would like to do is when I click on the outside of the modal after editing, I want the table back to the original form since I did not save it yet. Basically, I would like to prevent users' mistake if they edit the data then click outside of the modal. They'll think that data is updated since it reflects the table. However, this update is on the client side and it will back to original form when it's refreshed. How do I prevent this? Basically, my solution would be if the user clicks outside of the modal, modal closes. And I need to reset the edited part of the data in the table.

Here is a working code. Any help would be appreciated.

working sample on stackblitz

Upvotes: 1

Views: 2516

Answers (1)

AVJT82
AVJT82

Reputation: 73357

Objects are passed by reference, so essentially this.sample and the corresponding sample in the array points to the same object. You could pass the index instead and use the spread operator. So add the index to your iteration:

<tr *ngFor="let sample of samples; let i = index">

Pass the index to the click function:

(click)="updateSample(i, updateSampleModal)

and the function itself, where you have declared a variable index in your component:

updateSample(index: any, modal) {
  this.index = index;
  this.sample = { ...this.samples[index]};
  this.modalRef = this.modalService.show(modal,
    Object.assign({}, { class: 'gray modal-lg' })
  );
}

And if the save button is hit, assign the value to the specific sample in the array:

update(sample) {
  this.samples[this.index] = sample;
}

Your StackBlitz

Upvotes: 1

Related Questions