Angular2 ng-bootstrap: Reuse modal template with different data

╄→гoц情女王★ 提交于 2019-12-05 21:06:27

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!