Angular2 ng-bootstrap: Reuse modal template with d

2019-05-14 01:11发布

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?

2条回答
乱世女痞
2楼-- · 2019-05-14 01:51

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 the OnInit interface.

So the solution would be something like this:

constructor(
  private modalService: NgbModal
) { }

openModal() {
  const modalRef = this.modalService.open(MyComponent)
  modalRef.componentInstance.mycomponent_id = 1;
}

Your component look like this:

export class PlayerComponent implements OnInit {
  @Input() mycomponent_id;
  myObject: MyObject;

  ngOnInit() {
    this.myService.getObject(mycomponent_id)
      .subscribe(value => this.myObject = value);
  }
  ...
}

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 the ngOnInit() method which allow you to use the mycomponent_id value to fetch the correct data from your API using your service.

查看更多
等我变得足够好
3楼-- · 2019-05-14 02:01

You can open a modal window that holds a component from anywhere with the NgbModal service.

Call this.ngbModalService.open(NgbdModalContent) where NgbdModalContent is the component you are going to display in your modal.

Check out Components as content:

https://ng-bootstrap.github.io/#/components/modal

查看更多
登录 后发表回答