How pass data from ModalService into component

雨燕双飞 提交于 2019-12-20 05:32:25

问题


I'm trying to use ngx-bootstrap-modal to pass data from a modal service into a modal component. The examples show this:

this.modalService.show(ModalContentComponent, {initialState});

But it doesn't show how the ModalContentComponent actually consumes that state. I've played around in a debugger and I never see my component getting that data.

How do I access it from the component?


回答1:


You can also use the BsModalRef content Like

my-modal.component.ts

export class MyModalComponent {
  public myContent;
  constructor(){}
}

calling your modal from some other component

import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
...
    public modalRef: BsModalRef;

    constructor(public modalService: BsModalService){}

    public openModal() {
       this.modalRef = this.modalService.show(MyModalComponent);
       this.modalRef.content.myContent= 'My Modal Content';
    }
...



回答2:


At the stage of creating a modal, every property from initialState is copied to the component that you pass as a modal content.

For example, if your initialState looks like this:

const initialState = {
   list: [
     'Open a modal with component',
     'Pass your data',
     'Do something else',
     '...',
     'PROFIT!!!'
   ],
   title: 'Modal with component',
   closeBtnName: 'Close'
 };

Then all these properties are copied to your modal content component and they're accessible there and you can use them in your template or ngOnInit as usual. In general, these properties are like @Input.

Example - https://stackblitz.com/edit/angular-9n2zck?file=app/service-component.ts




回答3:


Since I can't yet comment on IlyaSurmay's answer...his solution works in 2.0.2 (but not in 2.0.0).



来源:https://stackoverflow.com/questions/48667781/how-pass-data-from-modalservice-into-component

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