How to reuse code snippets in TypeScript on Ionic 3

0

On one of my pages, when the user clicks the Delete button, an alert appears asking for confirmation. This action exists on more than one page, to avoid duplicate code, how can I reuse the method below? Should I move to some location, do some kind of include?

showConfirm(slidingItem: ItemSliding) {
    const confirm = this.alertCtrl.create({
      title: 'Deletar tarefa!',
      message: '<strong>Atenção</strong>: Essa ação não tem como ser desfeita.',
      buttons: [
        {
          text: 'Cancelar',
          handler: () => {
            slidingItem.close();
          }
        },
        {
          text: 'Deletar',
          handler: () => {
            slidingItem.close();
          }
        }
      ]
    });
    confirm.present();
  }

This code is executed by clicking on the element:

<button ion-button color="danger">
   <ion-icon name="delete"></ion-icon>
   Deletar
</button>
    
asked by anonymous 23.09.2018 / 03:12

1 answer

0

I was able to solve some of what I wanted with this component:

import { Component } from '@angular/core';
import { AlertController, ItemSliding } from 'ionic-angular';

@Component({})
export class ConfirmTaskDeletionComponent {

  constructor(public alertCtrl: AlertController) {}

  showConfirm(slidingItem: ItemSliding) {
    const confirm = this.alertCtrl.create({
      title: 'Deletar tarefa!',
      message: '<strong>Atenção</strong>: Essa ação não tem como ser desfeita.',
      buttons: [
        {
          text: 'Cancelar',
          role: 'cancel',
          handler: () => {
            slidingItem.close();
          }
        },
        {
          text: 'Deletar',
          handler: () => {
            slidingItem.close();
          }
        }
      ]
    });

    confirm.present();
  }

}

And I call it this:

showConfirm(slidingItem: ItemSliding) {
  this.dialog.showConfirm(slidingItem);
}

Already in my HTML (home page) I have:

<button ion-button color="danger" (click)="showConfirm(slidingItem)">
  <ion-icon name="delete"></ion-icon>
  Deletar
</button>

My challenge now is to move this button to the component's html, however, the (click)="showConfirm(slidingItem)" snippet is complicating my life, whenever I move it to work.

    
23.09.2018 / 18:58