在Angular 4的Bootstrap模式中将数据注入组件 [英] Inject data into component in Bootstrap Modal on Angular 4
问题描述
我正在使用@ ng-bootstrap/ng-bootstrap,它将Bootstrap组件添加到Angular.您可以将组件注入到打开的模态中,这样注入的组件就构成了打开的模态的主体/内容.
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.
我有一个Player
的列表.当我单击一个播放器时,我想在其中单击的播放器数据打开一个模态.我可以像这样用注入的PlayerComponent
打开一个模态.
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)
}
问题是... 我如何向组件注入其他数据,以使它知道要获取的玩家数据?我可能在PlayerComponent
上有一个OnInit
接口,该接口根据modalService.open()
调用提供的ID从API提取数据.
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.
推荐答案
似乎@ng-angular/ng-angular
允许您在实例化组件实例之后触摸它.因此,您可以修改这些值.
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.
因此解决方案是:
constructor(
private modalService: NgbModal
) { }
openPlayerModal() {
const modalRef = this.modalService.open(PlayerComponent)
modalRef.componentInstance.player_id = 1;
}
然后使组件在player_id
上使用@Input()
装饰器.
And then make the component use an @Input()
decorator on player_id
.
export class PlayerComponent {
@Input() player_id;
...
}
这篇关于在Angular 4的Bootstrap模式中将数据注入组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!