2
votes

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
I don't think you can do it with that service: github.com/ng-bootstrap/ng-bootstrap/blob/master/src/modal/… there isn't a parameter for additional data. The only way is to use a shared service it seems. - eko
Isn't it possible to instantiate the component before passing it to the open() method? - Marcus Lind
It is possible if you are using createComponent and it's resolver to dynamically create a component but idk how that works with the library you are using. - eko
I found a solution. Check it out below. - Marcus Lind
Glad you figured it out :-) - eko

1 Answers

7
votes

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;
  ...
}