Change variables in a modal

I’m trying to solve a problem where I open a modal with ModalController and then I want to change a variable in that modal later. Is this possible to do. It’s almost the same as “setContent” function for LoadingController but that doesn’t allow me to send in variables (Understandable from XSS pov and I don’t want to disable that).

I found that I can do “modal.overlay[‘instance’].variableName” but I don’t like that solution as it can break without me noticing.

So if I define a private variable in the Modal, is it possible for me to change that variable from the outside after then?

You can always use a service and observables…

pass a BehaviorSubject into the modal as a parameter. When you change the value of the BehaviorSubject in the calling component, the value in the Modal will get updated

Home Page

export class HomePage {

  // create BehaviorSubject
  something = new BehaviorSubject(new Date().getSeconds() + "")

  constructor(public navCtrl: NavController, public modalCtrl: ModalController) { }

  openBasicModal() {
    let myModal = this.modalCtrl.create(ModalPage, {
      update: this.something  // pass in  BehaviorSubject as data
    });
    myModal.present();

    setInterval(() => {
        this.something.next(new Date().getSeconds() + "")
    }, 1000)

  }
}

The Modal

import { Component } from '@angular/core';
import { NavController, NavParams, ViewController } from 'ionic-angular';

@Component({
  templateUrl: 'modal-page.html'
})
export class ModalPage {
  update: string;

  constructor(
    public viewCtrl: ViewController,
    params: NavParams
  ) {
   // get BehaviorSubject passed . in as parameter
    this.update = params.get('update');
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }
}

The Modal HTML

<ion-header>

  <ion-navbar>
    <ion-buttons start>
      <button ion-button (click)="dismiss()">Close</button>
    </ion-buttons>
    <ion-title>Modals</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
  <div [hidden]="!update">
    <h5>Parameters passed:</h5>
    <pre style="background-color: #f8f8f8"> {{update | async}} </pre>
  </div>
  <button ion-button color="danger" full (click)="dismiss()">Close Modal</button>
</ion-content>
2 Likes

Thanks for the answer, I tried this second one with the behavior subject and it worked perfectly. With the addition of subscribing to the subject in the modal like this.

let subject: BehaviorSubject<string> = this.navParams.get('update');
subject.subscribe((message) => this.theMessage = message);

Works well with the default value as well so I don’t need to send in the initial value of the message. So this is exactly what I needed. Thanks a lot again!

glad it worked out for you