Angular 7 - Power Tooltip on prime-table buttons

Asked

Viewed 239 times

0

I am using the prime-table, along with the tooltip, and would like the tooltip message to be customized for my system.

Ex: The edit button will display the "Edit user" message in the user table and the "Edit class" message in the class table.

inserir a descrição da imagem aqui (Where "edit" appears, the custom message)

Inside the prime-table component, I added generic buttons

prime-table.component.ts

import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import {TooltipModule} from 'primeng/tooltip';
// import * as html2canvas from 'html2canvas';
// import * as jsPDF from 'jspdf';
import { MessageService, SortEvent } from 'primeng/api';
// import { GeraExcelService } from 'services/gera-excel';
import * as FileSaver from 'file-saver';
interface Dados {
  id: number,
  nome_emp: string,
  nome_pessoa: string,
  data_verificacao: string,
  movimenta: string
}
@Component({
  selector: 'prime-table',
  templateUrl: './prime-table.component.html',
  styleUrls: ['./prime-table.component.css'],
  providers: [MessageService]

})
export class PrimeTableComponent implements OnInit {
  displayDialog: boolean;
  id: number;
  aux: any[] = null;
  car: any = {};
  datasource: Dados[];
  totalRecords: number;
  loading: boolean;
  selectedCar: any;
  newCar: boolean;
  dados: any[] = [];
  cols: any[];
  clonedCars: { [s: string]: Dados; } = {};
  @Input('titulo') titulo: string;
  //@Input('th') th : any[];
  @Output() outputAdd = new EventEmitter();
  @Output() outputEdita = new EventEmitter();
  @Output() outputVisualiza = new EventEmitter();
  @Output() outputDeleta = new EventEmitter();
  @Output() outputLista = new EventEmitter();
  @Output() outputGenerico = new EventEmitter();
  @Output() outputGenerico1 = new EventEmitter();
  @Output() outputGenerico2 = new EventEmitter();
  @Output() outputGenerico3 = new EventEmitter();
  @Output() outputGenerico4 = new EventEmitter();
  @Output() outputFiltro = new EventEmitter();
  @Input() btn_edita: boolean;
  @Input() btn_deleta: boolean;
  @Input() btn_visualiza: boolean;
  @Input() btn_cadastra: boolean;
  @Input() btn_generico: boolean;
  @Input() btn_generico1: boolean;
  @Input() btn_generico2: boolean;
  @Input() btn_generico3: boolean;
  @Input() btn_generico4: boolean;
  @Input() ativarToast: boolean;
  @Input('icone_generico') icon: string;
  @Input('icone_generico1') icon1: string;
  @Input('icone_generico2') icon2: string;
  @Input('icone_generico3') icon3: string;
  @Input('icone_generico4') icon4: string;
  @Input('td') set td(dados: any[]) {

    this.setTd(dados);
  }
  @Input('th') set th(dados: any[]) {
    this.setTh(dados);
  }

  //   onRowEditInit(car: Dados) {
  //     this.clonedCars[car.nome_pessoa] = {...car};
  // }
  setTd(dados) {

    if (this.ativarToast !== false) {
      // this.datasource = dados;
      // this.totalRecords = this.datasource.length;
      if (dados.length < this.dados.length) {
        this.showError();
      } else if (this.dados.length != 0 && dados.length > this.dados.length) {
        this.showSuccess();
      }
    }

    this.dados = null;
    this.dados = dados;

    // console.log(this.cars);
  }

  setTh(dados) {
    this.cols = [];
    this.cols = dados;
  }
  constructor(private messageService: MessageService,
    ) {

  }

  ngOnInit() {

  }
  showSuccess() {
    this.messageService.add({ severity: 'success', summary: 'Aviso!', detail: 'Item adicionado' });
  }

  showError() {
    this.messageService.add({ severity: 'error', summary: 'Aviso!', detail: 'Item removido' });
  }

  clear() {
    this.messageService.clear();
  }


  getKeys(obj) {
    return Object.entries(obj)
  }

  getValues(obj) {
    //console.log('teste',obj)
    return Object.values(obj)
  }

  //   showDialogToAdd() {
  //     this.outputAdd.emit();
  //     // this.newCar = true;
  //     // this.car = {};
  //     // this.displayDialog = true;
  // }

  edita(id) {
    this.outputEdita.emit(id);
  }
  add() {
    this.outputAdd.emit();
  }

  filtro() {
    this.outputFiltro.emit();
  }

  deleta(id) {

    this.outputDeleta.emit(id);
  }

  visualiza(id) {
    this.outputVisualiza.emit(id);
  }

  toastDeleta(id) {
    this.id = null;
    this.id = id;
    this.messageService.add({
      key: 'c', sticky: true, severity: 'warn',
      detail: ' Deseja excluir este item? '
    });
  }

  confirmaDeleta() {
    this.deleta(this.id);
    this.messageService.clear('c');
  }

  cancelaDeleta() {
    this.messageService.clear('c');
  }

  save() {
    // let dados = [...this.dados];
    // if (this.newCar)
    // dados.push(this.car);
    // else
    // dados[this.dados.indexOf(this.selectedCar)] = this.car;

    // this.dados = dados;
    // this.dados = null;
    // this.displayDialog = false;
  }

  delete() {
    // let index = this.cars.indexOf(this.selectedCar);
    // this.cars = this.cars.filter((val, i) => i != index);
    // this.car = null;
    // this.displayDialog = false;
  }

  onRowSelect(event) {
    //this.outputAdd.emit();

    // this.newCar = false;
    // this.car = this.cloneCar(event.data);
    // this.displayDialog = true;
  }

  generico(dados) {
    this.outputGenerico.emit(dados);
  }
  generico1(dados) {
    this.outputGenerico1.emit(dados);
  }

  generico2(dados) {
    this.outputGenerico2.emit(dados);
  }

  generico3(dados) {
    this.outputGenerico3.emit(dados);
  }

  generico4(dados) {
    this.outputGenerico4.emit(dados);
  }

  // gerarExcel() {
  //   var table = []

  //   table.push({
  //     ths: this.cols, tds: this.dados, nomeArquivo: ''
  //   })
  //   this.geraExcelService.geraExcel(JSON.stringify(table)).subscribe((response: any) => {

  //     let blob = new Blob([response], { type: 'application/vnd.ms-excel' })
  //     FileSaver.saveAs(blob, 'Tabela_Intranet_.xls')
  //   })

  // }

  customSort(event: SortEvent) {
    const mes = { Janeiro: 1, Fevereiro: 2, Março: 3,    Abril: 4,    Maio: 5,      Junho: 6,
                  Julho: 7,   Agosto: 8,    Setembro: 9, Outubro: 10, Novembro: 11, Dezembro: 12 };
    event.data.sort((data1, data2) => {
      let value1 = data1[event.field];
      let value2 = data2[event.field];
      let result = null;

      if (value1 == null && value2 != null) {
        result = -1;
      } else if (value1 != null && value2 == null) {
        result = 1;
      } else if (value1 == null && value2 == null){
        result = 0;
      } else if (typeof value1 === 'string' && typeof value2 === 'string' && event.field !== 'mes') {
        result = value1.localeCompare(value2);
      } else if (event.field === 'mes') {
        result = (mes[value1] < mes[value2]) ? -1 : (mes[value1] > mes[value2]) ? 1 : 0;
      } else {
        result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
      }
      return (event.order * result);
    });
  }

}

prime-table.component.html.ts


<div *ngIf="this.titulo != null" class="barra_titulos">{{titulo}}</div>

<div class="row mt-4 " style="margin-right:0px; ">

        <div class="col-4">
                <div class="ui-g ui-fluid">
                        <div class="ui-inputgroup">
                                <button class="btn btn-sm btn-warning mb-1 ml-1" (window:keydown.f2)="filtro(); filtro_toast = true;"   (click)="filtro(); filtro_toast = true;"  ><i class="fa fa-filter" title="Filtrar dados"></i></button>
                                <button class="btn btn-sm btn-outline-dark mb-1 mx-1" (click)="gerarExcel()" ><i class="fa fa-file-excel" title="Exportar para Excel"></i></button>
                                <!-- <button class="btn btn-sm btn-outline-dark mb-1 mx-1" (click)="exportPDF()" ><i class="fa fa-file-excel" title="Exportar para Excel"></i></button>   -->

                        </div>
                        <div class=" mb-1 ui-inputgroup">

                            <span class="ui-inputgroup-addon" style="border-right:0px !important;"><i class="fa fa-search"></i></span>
                            <input   style="padding-left:5px !important; " type="text" pInputText placeholder="Buscar" (input)="dt.filterGlobal($event.target.value, 'contains')" >

                </div>
            </div>

        </div>
        <div class="col-8">
                <div class="mt-2 float-right">
                        <button *ngIf="btn_cadastra" class="btn btn-sm btn-warning mb-1" (click)="add()"   ><i class="fa fa-plus" title="Cadastrar"></i>  Cadastrar</button>

                        <!-- <button type="button" pButton icon="fa fa-plus" (click)="showDialogToAdd()" label="Add"></button> -->

                </div>
        </div>

</div>


<p-table #dt   [columns]="cols" [value]="dados"  [paginator]="true"
[rows]="10"  [reorderableColumns]="true" id="tabela" [autoLayout]="true" (sortFunction)="customSort($event)" [customSort]="true">

    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of cols" [pSortableColumn]="col.field" [ngStyle]="{width: col.width}" pReorderableColumn >
                {{col.header}}
                <p-sortIcon [field]="col.field"></p-sortIcon>
            </th>

        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns" let-index="rowIndex">
        <tr [pSelectableRow]="rowData" [pReorderableRow]="index" >
             <ng-container  *ngFor="let col of cols" >
                      <td *ngIf="col.field == 'id'; else elseTemplate " style="text-align:center">
                                <button *ngIf="btn_visualiza" class="  btn btn-sm btn-outline-dark" (click)="visualiza(rowData[col.field]);filtro_toast = false;" pTooltip="Visualizar" tooltipPosition="top">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button *ngIf="btn_edita" class=" mx-1 btn btn-sm btn-outline-dark" (click)="edita(rowData[col.field]); filtro_toast = false;" pTooltip="Editar" tooltipPosition="top">
                                    <i class="fas fa-pencil-alt" title="Editar movimentação"></i>
                                </button>
                                <button *ngIf="btn_generico" class="mx-1  btn btn-sm btn-outline-dark" (click)="generico(rowData); filtro_toast = false;" >
                                        <i [class]="icon"></i>
                                </button>
                                <button *ngIf="btn_generico1" class=" mx-1 btn btn-sm btn-outline-dark" (click)="generico1(rowData); filtro_toast = false;" >
                                        <i [class]="icon1"></i>
                                </button>
                                <button *ngIf="btn_generico2" class=" mx-1 btn btn-sm btn-outline-dark" (click)="generico2(rowData); filtro_toast = false;" >
                                        <i [class]="icon2" ></i>
                                </button>
                                <button *ngIf="btn_generico3" class=" mx-1 btn btn-sm btn-outline-dark" (click)="generico3(rowData); filtro_toast = false;" >
                                        <i [class]="icon3" ></i>
                                </button>
                                <button *ngIf="btn_generico4" class=" mx-1 btn btn-sm btn-outline-dark" (click)="generico4(rowData); filtro_toast = false;" >
                                        <i [class]="icon4" ></i>
                                </button>
                                 <button *ngIf="btn_deleta" class=" mx-1 btn btn-sm btn-outline-dark" (click)="toastDeleta(rowData[col.field]); filtro_toast = false;" >
                                    <i class="fas fa-trash-alt" title="Excluir item"></i>
                                </button>

                        </td>
                        <ng-template #elseTemplate >
                                <td >
                                        {{rowData[col.field]}}
                                    <!-- <p-cellEditor>
                                           <ng-template pTemplate="input">
                                               <input pInputText type="text" [(ngModel)]="rowData[col.field]">
                                           </ng-template>
                                           <ng-template pTemplate="output">
                                                   {{rowData[col.field]}}
                                           </ng-template>
                                       </p-cellEditor>             -->
                                  </td>
                        </ng-template>

                      <!-- <td >
                            <button class="  btn btn-sm btn-outline-dark" >
                                <i class="fas fa-eye"> {{rowData[col.field[rowIndex].id]}}</i>
                            </button>

                      </td> -->
             </ng-container>

        </tr>
    </ng-template>
    <!-- <ng-template pTemplate="summary" let-rowData>
        <div style="text-align:left">
            <button type="button" pButton icon="fa fa-plus" (click)="showDialogToAdd()" label="Add"></button>
        </div>
    </ng-template>     -->
</p-table>

<div *ngIf="dados.length == 0 " class="alert alert-danger">
    Sem dados para exibir
</div>
<!-- <p-dialog header="Car Details" [(visible)]="displayDialog" [responsive]="true" showEffect="fade" [modal]="true"  [style]="{width: '300px'}">
    <div class="ui-g ui-fluid" *ngIf="car">
        <div class="ui-g-12">
            <div class="ui-g-4">
                <label for="vin">Vin</label>
            </div>
            <div class="ui-g-8">
                <input pInputText id="vin" [(ngModel)]="car.vin" />
            </div>
        </div>
        <div class="ui-g-12">
            <div class="ui-g-4">
                <label for="year">Year</label>
            </div>
            <div class="ui-g-8">
                <input pInputText id="year" [(ngModel)]="car.year" />
            </div>
        </div>
        <div class="ui-g-12">
            <div class="ui-g-4">
                <label for="brand">Brand</label>
            </div>
            <div class="ui-g-8">
                <input pInputText id="brand" [(ngModel)]="car.brand" />
            </div>
        </div>
        <div class="ui-g-12">
            <div class="ui-g-4">
                <label for="color">Color</label>
            </div>
            <div class="ui-g-8">
                <input pInputText id="color" [(ngModel)]="car.color" />
            </div>
        </div>
    </div>
    <p-footer>
        <div class="ui-dialog-buttonpane ui-helper-clearfix">
            <button type="button" pButton icon="fa fa-close" (click)="delete()" label="Delete"></button>
            <button type="button" pButton icon="fa fa-check" (click)="save()" label="Save"></button>
        </div>
    </p-footer>
</p-dialog> -->


<p-toast [style]="{marginTop: '80px'}"></p-toast>
<p-toast position="center" key="c" (onClose)="onReject()" [modal]="true" [baseZIndex]="5000">
    <ng-template let-message pTemplate="message">
        <div style="text-align: center">
            <i class="fas fa-exclamation-circle" style="font-size: 3em; color:#e85b5b !important;"></i>
            <h3>{{message.summary}}</h3>
            <p>{{message.detail}}</p>
        </div>
        <div class="ui-g ui-fluid">

            <div class="ui-g-12">
                   <button class=" btn  btn-outline-success" (click)="confirmaDeleta()">
                     <i class="fas fa-check"  style="color:green !important;"></i> Confirmar
                 </button>

                 <button class="ml-2  btn  btn-outline-danger" (click)="cancelaDeleta()">
                     <i class="fas fa-times"  style="color:#e85b5b !important;"></i> Cancelar
                 </button>
            </div>


        </div>
    </ng-template>
</p-toast>

In this case, I have to send the message when I call the event, but I have no idea how to receive this msg to put inside a "pTooltip" buttons in the html file of the prime-table.

1 answer

0


I solved it like this, I created @Input for Tooltips, and it was like this:

<prime-table [th]="th" *ngIf="perfis.length > 0" [td]="perfis"
  [btn_cadastra]="true" [ptooltip_cadastrar]="'Criar Perfil'" (outputAdd)="onCreate()"
  [btn_edita]="true" [ptooltip_editar]="'Editar Perfil'" (outputEdita)="onEdit($event)"
  [btn_deleta]="true" [ptooltip_deletar]="'Deletar Perfil'" (outputDeleta)="onDelete($event)"
  [btn_generico1]="true" [ptooltip_generico1]="'Acrescentar Permissões'" [icone_generico1]="'fas fa-plus'" (outputGenerico1)="onAdd($event)"
  [btn_generico2]="true" [ptooltip_generico2]="'Modificar Permissões'" [icone_generico2]="'fas fa-tasks'" (outputGenerico2)="onModify($event)"
></prime-table>

In the table file:

@Input() ptooltip_editar: string;
  @Input() ptooltip_deletar: string;
  @Input() ptooltip_visualizar: string;
  @Input() ptooltip_cadastrar: string;
  @Input() ptooltip_generico: string;
  @Input() ptooltip_generico1: string;
  @Input() ptooltip_generico2: string;
  @Input() ptooltip_generico3: string;
  @Input() ptooltip_generico4: string;

And in the component of that file was like this:

<button *ngIf="btn_cadastra == '2'" disabled class="btn btn-sm btn-warning mb-1" (click)="add()" pTooltip="{{ptooltip_cadastrar}}" tooltipPosition="left"><i class="fa fa-plus" ></i>  Cadastrar</button>

Browser other questions tagged

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