Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ng-click using TypeScript and ionicBootstrap?

I'm not sure how the ng-click works in Ionic 2 with Typescript.

Basically, my Ionic app looks like this:

class MyApp { 
 ...
 showPopup() { .. } 
 ...
}
ionicBootstrap(MyApp);

Edit: I also tried adding the function in the specific-page.ts file, but it doesn't work.

I try to use the showPopup() inside an ng-click but obviously, there's something missing, and I can't find any information about it in the documentation.

ng-click="showPopup()"

Do you have any idea what I am missing? I know without Typescript $scope must be used, but what about with Typescript and IonicBootstrap?

like image 276
Kevin Van Ryckegem Avatar asked Dec 24 '22 19:12

Kevin Van Ryckegem


2 Answers

Ionic2 is based on Angular 2 and the proper way to use the click event (docs) is

// component code
import { Component } from "@angular/core";

@Component({
  templateUrl:"home.html"
})
export class HomePage {

  public items: Array<string>;

  constructor() {
    this.items = ["item1", "item2", "item3"]
  }

  public open(event, item) {
    alert('Open ' + item);
  }

}

And then in your view

<!-- View -->
<ion-header>
  <ion-navbar primary>
    <ion-title>
      <span>My App</span>
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-list>
    <ion-item *ngFor="let item of items" (click)="open($event, item)">
        {{ item }}
    </ion-item>
</ion-list>
</ion-content>

As you can see in the code, I'm declaring the click handler like this (click)="open($event, item)" and sending both the event and the item (declared in the *ngFor) to the open() method (declared in the component code).

If you don't need to get info from the event, you can just do (click)="open(item)" and modify the open method like this public open(item) { ... }

like image 136
sebaferreras Avatar answered Dec 28 '22 09:12

sebaferreras


In your html component, that you want it to be clickable, you need to use (click)='showPopup()'. Like say:

<button (click)='showPopup()'>Click here</button>

In your typescript, the code is correct:

class MyApp { 
 ...
 showPopup() { .. } 
 ...
}

Additionally you can pass parameters as you would normally pass. (click)=showPopup(param1,param2,..).

like image 38
Sagar Kulkarni Avatar answered Dec 28 '22 10:12

Sagar Kulkarni