I’m trying to understand some concepts and wanted to see if anyone could help. I’ve got an ng-bootstrap modal displaying some information that’s being input from the API call being made in the Parent Component. Basically, I’m displaying data in this modal and I'm able to hit the delete route to remove some records. That's all fine but the issue I have is when I close the modal, I want the parent component to refresh and not show the records which were just deleted from the modal, so basically running the request again and updating the information, but I’m not sure how to accomplish this. I believe usually this could be done with event emitter perhaps but I’m stuck since I’m doing this from a modal and using ng-bootstrap. Any help in understanding this would be much appreciated!
Here’s my code:
app.html:
<div>
<ul>
<li *ngFor="let user of users">{{user.first_name}}</li>
</ul>
<button (click)="openFormModal()" class="btn btn-primary btn-sm">view more</button>
</div>
app.ts:
export class AppComponent {
users: any;
constructor(private api: ApiService,
private modalService: NgbModal) {}
ngOnInit() {
this.getUsers();
}
openFormModal(){
const modalRef = this.modalService.open(DetailsModalComponent);
modalRef.componentInstance.users = this.users;
modalRef.result.then((result)=> {
console.log(result);
}).catch((error) => {
console.log(error);
});
}
getUsers() {
this.api.getUsers().subscribe(data => {
this.users = data;
})
}
}
details-modal.html:
<div class="modal-header">
<h4 class="modal-title">Modal Title</h4>
<button type="button" class="close" aria-label="Close"
(click)="closeModal()">
</button>
</div>
<div class="modal-body">
<p *ngFor="let user of users">{{user.first_name}} <span (click)="deleteUser(this.user.id)" style="cursor: pointer">DELETE</span></p>
</div>
<div class="modal-footer">
<button (click)="closeModal()">
Close Clicked
</button>
</div>
details-modal.ts:
@Component({
selector: 'app-details-modal',
templateUrl: './details-modal.component.html',
styleUrls: ['./details-modal.component.css']
})
export class DetailsModalComponent implements OnInit {
@Input() users;
constructor(
public activeModal: NgbActiveModal,
private api: ApiService
) {}
ngOnInit() {
}
fetch() {
this.api.getUsers().subscribe(data => {
this.users = data;
})
}
closeModal() {
this.activeModal.close()
}
deleteUser(id) {
this.api.deleteUser(id).subscribe(data => {
this.fetch();
})
}
}
Apparently from this GitHub post, you can do this
modalRef.result.then(
() => {
console.log("Close button clicked");
// actions
},
()=> {
console.log("Close icon clicked or backdrop clicked");
// actions
});
Stackblitz: https://stackblitz.com/edit/angular-ey8hkm