如何将组件的更改从一个页面反映到另一个页面

时间:2017-10-30 06:37:37

标签: angular typescript ionic2 ionic3

我有选择选项控件,它将出现在许多页面中,因此我创建了一个页面并将该选项放入该页面并在其他页面中调用该页面。当我在第1页中使用此组件并且所选值在第2页中使用输入和输出反映时,但在第2页和关闭第2页中所做的更改未在第1页中反映,所以任何人都可以帮我解决此问题吗?到目前为止我做了什么......

定制NAV-一个bar.html

<ion-toolbar>
  <ion-navbar primary>

        <ion-item text-wrap>
          <!-- <ion-label>Gaming</ion-label> -->

          <ion-select interface="popover" (ionChange)="onChange()" [(ngModel)]="choose">
            <ion-option [value]="cg" *ngFor="let cg of chArr;" >{{cg.fname}}</ion-option>
          </ion-select>

        </ion-item>
      </ion-navbar>
</ion-toolbar>

定制NAV-bar.ts

@Component({
  selector: 'page-custom-nav-bar',
  templateUrl: 'custom-nav-bar.html',
  inputs: ['chArr', 'choose'],//choose as input to get input from the pages for ngModel
  outputs: ['optionpageselection']
})
export class CustomNavBarPage {

  choose: any;
  optionpageselection: EventEmitter<string> = new EventEmitter<string>();

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad CustomNavBarPage');
  }


  onChange() {
    console.log("onchange called in custNav")

    this.optionpageselection.emit(this.choose);

  }
}

1页

export class page1 {
      choose: any;

onChange(event) {
    this.choose = event;
    console.log("you have selected")
    console.log(this.choose);
  }
}

page1.html

<ion-header>

  <page-custom-nav-bar [chArr]="chArr" [choose]="choose" (optionpageselection)="onChange($event)" ></page-custom-nav-bar>
</ion-header>


<ion-content padding>
</ion-content>

page2.html

<ion-header>

  <page-custom-nav-bar [chArr]="chArr" [choose]="choose" (optionpageselection)="onChange($event)" ></page-custom-nav-bar>
</ion-header>

<ion-content>
</ion-content>

page2.ts

export class page2{
  chArr: any;
  choose: any;

constructor(public navCtrl: NavController,
    public navParams: NavParams, private storage: Storage,
    public alertCtrl: AlertController) {

    this.chArr = navParams.get('chArr');
    this.choose = navParams.get('choose');
    console.log('choose ' + this.choose);


  }
onChange(event) {
    this.choose = event;
    console.log("you have selected in page2")
    console.log(this.choose);
}
}

2 个答案:

答案 0 :(得分:2)

ionViewWillEnter() {
    this.myData = this.navParams.get('myDataKey') || null;
}

ionViewWillLeave() {
    this.navCtrl.getPrevious().data.myDataKey = this.myData;
}

答案 1 :(得分:0)

另一种方法是使用Storage module

定制NAV-bar.ts

onChange() {
    this.storage.set('choose', this.choose);//you can retrive this value from anywhere
  }

page2.ts

ionViewDidEnter(){
    this.storage.get('choose').then((val) => {
        let choose = val;
      });
}