Home > Blockchain >  Ionic/Angular - Run method with name from html
Ionic/Angular - Run method with name from html

Time:02-16

I have a menu in an Ionic Angular application.

<ion-menu-toggle auto-hide="false" *ngFor="let p of menuItems; let i = index">
   <ion-item button (click)=p.method >
       <ion-icon slot="start" [ios]="p.icon   '-outline'" [md]="p.icon   '-sharp'"></ion-icon>
   </ion-item>
</ion-menu-toggle>
    public menuItems = [
    { title: 'New', method: this.newFile, icon: 'add' },
    { title: 'Open', method: this.openFile, icon: 'download' },
    { title: 'Save', method: this.saveFile, icon: 'save' },
    { title: 'Export', method: this.exportFile, icon: 'archive' }
    ]
    
    newFile(){ console.log("New");}
    openFile(){ console.log("Open");}
    ...

But the button click does nothing.

Is there a way to pass the method with the list or am i forced to have a method with a switch ?

   <ion-item button (click)=menuSwitch(p.method) >

    menuSwitch(item){
        if(item == 'New')
            NewFile();
        ...
    }

CodePudding user response:

Of course you can do it. This is JS. You can do any thing. Just change your click like below

  <ion-menu-toggle auto-hide="false" *ngFor="let p of menuItems; let i = index">
    <ion-item button (click)="p.method()">
      <ion-icon slot="start" [ios]="p.icon   '-outline'" [md]="p.icon   '-sharp'"></ion-icon>
    </ion-item>
  </ion-menu-toggle> 
  • Related