How to pass data from page to modal in ionic 4 app?

In my ionic app, I am trying to navigate from a page to a modal, & display some data which I passed to the Modal.

Below I am creating an ActionSheet & assigning a button to display the modal:

this.actionSheet.buttons = [
{
          text: 'View all comments',
          handler: () => {          
            this.modalCtrl.create({
              component: CommentsPage,
              componentProps: {
                'post': post
              }
            }
            ).then(modal => {
              this.modal = modal;
              modal.present();
            });
          }
        }
];

The modal successfully appears with blank code like so:

export class CommentsPage implements OnInit {
  post: any = {};
  constructor() { }
  ngOnInit() {
  }
}

But I want to get the post data which I added to the componentProps inside the ModalController.

I tried to retrieve this using ActivatedRoute below, but am getting this error:

Property ‘activatedRoute’ does not exist on type ‘CommentsPage’.ts

export class CommentsPage implements OnInit {
  post: any = {};
  constructor(activatedRoute: ActivatedRoute) { }
  ngOnInit() {
    this.post = this.activatedRoute.snapshot.paramMap.get('myid');
  }
}

Am I passing the post value correctly? If so, how can I use that value inside the modal?

In the Modal, declare the Parameter as an Input like:

@Input()
post: any;

Furthermore:

  • Try to avoid any Types
  • you don’t need the ' in the componentProps:
    componentProps: {
        post
    }
    

Thanks for the quick reply. I’ve incorporated your changes, but the ActivatedRoute error mentioned in the question is still appearing.

Remove the Route, as you don’t need it. If you use the @Input the Parameter is directly available on Init.
As the Modal isn’t created over Routing, the Activated Route doesn’t work in there.

1 Like