Search code examples
javascriptangularionic-frameworkmodal-dialog

How to pass an object from page to modal component in Angular 12


i want to pass an object ( media: any={}; ) to a modal component to show media parameters like id etc.

This is what i have so far.

HTML PARENT COMPONENT

<ion-button fill="clear" (click)="modalPoints(media)">

TYPESCTIPT PARENT COMPONENT

export class HomePage implements OnInit {
    @ViewChild('modal') modal: GivePointsComponent;
    media: any = {};

async modalPoints(media) {
        this.media= media;
        const modal = await this.modalCtrl.create({
            component: GivePointsComponent,
            breakpoints: [0, 0.4, 1],
            initialBreakpoint: 0.4,
            cssClass: 'custom-modal'
        });
        this.modal.media = this.media;
    }

TYPESCRIPT CHILD MODAL COMPONENT (GivePointsComponent.ts)

export class GivePointsComponent implements OnInit {
  @Input() media:any;

HTML MODAL COMPONENT (GivePointsComponent.html)

<app-modal-component #modal>
        <ion-label >{{media.msg_id}}<br>
          {{media.msg_id}}</ion-label>
</app-modal-component>

I should be getting the media.msg_id instead i am getting this as error on console;l

core.mjs:6469 ERROR Error: Uncaught (in promise): TypeError: Cannot set properties of undefined (setting 'media')
TypeError: Cannot set properties of undefined (setting 'media')

Solution

  • You pass data tp the modal by using it as componentProps like this:

      async openModal(media: any)
      {
        let modal = await this.modalctrl.create({
          component: GivePointsComponent,
          componentProps: {media: media},
        });
        modal.present();
        modal.onDidDismiss().then(() => console.log('dismiss'));
      }
    

    You get an error because you dont provide media -> media undefined error