Ionic 4 how do I receive componentProps?

南楼画角 提交于 2019-12-10 14:19:55

问题


In Ionic 4, I am trying to use the modalController to open a modal. I am able to open the modal and send componentProps, but I'm not sure how to receive those properties.

Here's how I open the modal component:

async showUpsert() {
  this.modal = await this.modalController.create({
    component:UpsertComponent,
    componentProps: {test: "123"}
  });
  return await this.modal.present();
}

My question is; in the actual modal, how do I get test: "123" into a variable?


回答1:


You can take those values with Input Component Interaction in the component you will need it, for example:

import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { TestComponent } from '../test/test.component';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
  constructor(public modalController: ModalController){}
  async presentModal() {
    const modal = await this.modalController.create({
      component: TestComponent,
      componentProps: { value: 123, otherValue: 234 }
    });
    return await modal.present();
  }
}

In your modal component with Input you can take those params:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
  @Input("value") value;
  @Input() otherValue;
  constructor() { }

  ngOnInit() {
    //print 123
    console.log(this.value);
    //print 234
    console.log(this.otherValue);
  }
}



回答2:


You can also use Navparams to get the value of componentProps.

import { CommentModalPage } from '../comment-modal/comment-modal.page';
import { ModalController, IonContent } from '@ionic/angular';


constructor(public modalCtrl : ModalController) {  }

  async commentModal() {
      const modal = await this.modalCtrl.create({
        component: CommentModalPage,

        componentProps: { value: 'data'}
      });
      return await modal.present();
   }

In your commentModalPage, you just have to import navprams and get the value from it.

import { NavParams} from '@ionic/angular';

constructor(public navParams : NavParams) {  

              console.log(this.navParams.get('value'));

            }



回答3:


just add the following to your modal page:

public test: string;

then you may test it with:

console.log(this.test); // Output will be '123'

source



来源:https://stackoverflow.com/questions/51989882/ionic-4-how-do-i-receive-componentprops

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