How to reuse snippets of code in Typescript in Ionic 3

Asked

Viewed 93 times

0

On one of my pages, when the user clicks the button Delete an Alert is displayed requesting confirmation. This action exists on more than one page, to avoid duplicating code, how can I reuse the method below? Should I move somewhere, 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>

1 answer

0

I managed to solve part of what I wanted with this:

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 him that:

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

Already in my HTML (main 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 html of the Component, however, the snippet (click)="showConfirm(slidingItem)" is complicating my life, whenever the motion stops working.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.