Getting data from Modal Controller

Hello
for getting data in opened modal in official documentation was written this example

async presentModal() {
  const modal = await this.modalController.create({
    component: ModalPage,
    componentProps: {
      'firstName': 'Douglas',
      'lastName': 'Adams',
      'middleInitial': 'N'
    }
  });
  return await modal.present();
}

To get the data passed into the componentProps, either set it as an @Input or access it via NavParams on the ModalPage:

export class ModalPage {

  // Data passed in by componentProps
  @Input() firstName: string;
  @Input() lastName: string;
  @Input() middleInitial: string;

  constructor(navParams: NavParams) {
    // componentProps can also be accessed at construction time using NavParams
    console.log(navParams.get('firstName'));
  }

}


BUT

I also can get data like this —

async presentModal() {
  const modal = await this.modalController.create({
    component: ModalPage,
    componentProps: {
      firstName: 'Douglas',
     
    }
  });
  return await modal.present();
}

and for getting data in Modal, for example, the value of - firstName,
I can do it in ngOnInit life hook

export class ModalPage {

public firstName : string
  constructor( ) {
      
  }
ngOnInit(){
console.log(this.firstName)  // output will be -  'Douglas'
}
}

So I want to know is this an error? or it is normal behavior for the modal controller???

I would not use navParams. Use the @Input binding approach.

Since @Input is just a decorator, and it doesn’t really modify the property bindings, yes I would expect the second example to still work.

@Input just lets angular know what properties can be passed to a component.

1 Like

Hello Mmartington
Thank you for your response. But how I understand, the Ionic Modal component is an encapsulated component and we can not get data from other components directly. but in my example, I got the “firstName” value from the parent component by using “this.firtsName” in Modal component itself, without using “Navparams” or “@Input

Thanks

I believe what @mhartington is saying is that the Ionic code that magically stuffs values into overlay controllers (a generic term for "components popped by things like ModalController") is independent of whether the property in question is decorated by @Input. Perhaps this is a side-effect of changes made to the Ionic Framework to work with subframeworks other than Angular.

What I’m saying is that the way modal’s are constructed, they will set the property regardless.

If we think of the component as an object…

ModalComponent = {}
ModalComponent.foo = 'bar'

// this is the same as
//
ModalComponent = {
  foo: null
}

ModalComponent.foo = 'bar'