[Ionic 4] Passing a TS variable to a HTML page

So, I see in a lot of places that if I want to pass a .ts variable to the HTML I have just to declare this var in the .ts page, set a value and then call this variable with {{}} in the HTML page.

Some links that say this:
ionic forum question
angular cheatsheet
SO question 1
SO question 2

I’m trying to populate a modal with some data that I already have, so the user can edit if he wants. I don’t know if I’m doing something wrong or if there is any change in ionic 4.

My .TS:

export class ModalPointPage implements OnInit {
  public modalName: string;

  constructor () {
    ...
  }
  ngOnInit () {
    ...
    this.modalName = this.navParams.data.paramName;
  }
}

My HTML:

<ion-item>
	  <ion-label position="floating">Name: </ion-label>
	  <ion-input type="text" id="name">{{modalName}}</ion-input>
</ion-item>

I already tried to define the variable value inside the constructor, inside the ngOnInit and with the variable definition above the constructor. The value just don’t pass, the “name” field keeps empty.

You need to set it as a value.

 <ion-input type="text" id="name" name="some_name" value="{{modalName}}"></ion-input>

Forgot to tell, but already tried this too. Sadly still got an empty field.

What does modalName have by default? I hope it isn’t undefined when the view is rendered.

By default, is defined inside ngOnInit(), the same way as in the ion-modal doc.

...
ngOnInit() {
    //Some data that came from the main page
    this.modalName = this.navParams.data.paramName;
}
...

Note that I can see the variable value with console.log. And as mentioned before, I already tried to define in other places and with other values.

Well, I don’t usually use ngOnInit() when it comes to ionic pages.
Can you try this inside ionViewWillLoad() ? This gets fired before view is loaded.

ionViewWillLoad(){
   //Some data that came from the main page
    this.modalName = this.navParams.data.paramName;
}

and in your view file as

<ion-input type="text" id="name" name="some_name" value="{{modalName}}"></ion-input>
1 Like

Basically just removing everything inside ngOnInit solved the problem. But I don’t know if is related to undefined values before the render because I use the async method to open/dismiss the modal. I really appreciate your help, thanks a lot! I hope this helps someone else in the future.

Another thing, to see the value in the view I need to pass the {{}} value inside the tag:
<ion-input type="text" id="name" name="some_name" value="{{modalName}}">{{modalName}}</ion-input>

1 Like

I am glad I could help :slight_smile: