I am building a dashboard-like interface with a set of entities containing comparable data. Each of these entities have an edit-button which I would like to use to open a modal with the respective data displayed.
I would like to reuse the same modal template, and display the data from the entity who's edit-button was clicked. I am using Angular2 with ng-bootstrap, which relies on Bootstrap 4.
From the ng-bootstrap modal docs, and it's accompanying plunkr, I was able to create my own working modal component like so (simplified for layout):
//editmodal.html
<template #content let-c="close" let-d="dismiss">
//Modal html content
</template>
<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Edit</button>
//dashboard.html
<template ngbModalContainer></template>
<edit-modal></edit-modal>
//editmodal.component.ts
@Component({
selector: 'edit-modal',
templateUrl: 'entity/assets/templates/editmodal.html'
})
export class EditModal {
//exported class logic
}
The main thing which struck me as odd, coming from the previous bootstrap version, is that the button to open the modal is now displayed within the template itself, encapsulating it. This makes it hard to attach a reference to it so I could figure out what to show from the class logic. How can I achieve this behaviour with Angular2 and ng-bootstrap?
Similar to what Lev wrote in his answer, you can use the
NgbModal.open()
method and pass it a component to populate the content of a modal.Now, you don't just want a component. You also want the component to fetch the data from an API. You can do this by combining the
NgbModalRef.componentInstance
parameter, with theOnInit
interface.So the solution would be something like this:
Your component look like this:
So basically to summarize it. You open the modal by passing it the component you want as content. Then you set the
mycomponent_id
value from outside your component. After this your component will run thengOnInit()
method which allow you to use themycomponent_id
value to fetch the correct data from your API using your service.You can open a modal window that holds a component from anywhere with the
NgbModal
service.Call
this.ngbModalService.open(NgbdModalContent)
whereNgbdModalContent
is the component you are going to display in your modal.Check out Components as content:
https://ng-bootstrap.github.io/#/components/modal