Inject data into component in Bootstrap Modal on Angular 4

你说的曾经没有我的故事 提交于 2019-12-11 02:07:32

问题


I'm using the @ng-bootstrap/ng-bootstrap which adds Bootstrap components to Angular. You can inject components into an opened Modal, so the injected component makes up the body/content of the opened modal.

I have a list of Player. When I click a player, I want to open a Modal with the clicked player's data inside of it. I can open a Modal with the injected PlayerComponent like this.

constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
}

The question is... How do I inject additional data to the component to let it know what player's data to fetch? E.g. I might have an OnInit interface on the PlayerComponent that fetches data from an API based on an ID supplied by the modalService.open() call.


回答1:


It seems like @ng-angular/ng-angular allow you to touch the component instance after it has been instantiated. So you can then modify the values.

So solution would be:

constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
  modalRef.componentInstance.player_id = 1;
}

And then make the component use an @Input() decorator on player_id.

export class PlayerComponent {
  @Input() player_id;
  ...
}


来源:https://stackoverflow.com/questions/44410418/inject-data-into-component-in-bootstrap-modal-on-angular-4

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