Yesub
Yesub

Reputation: 437

Angular 5 (onClick) event firing twice

I have a component using a button :

<dx-button text="{{'VIEW_DATA.BUTTON.EXPORT_TO_EXCEL' | translate }}" type="normal" (onClick)="export()" ></dx-button>

In the .ts file I do :

export() {
  let cells = [];
  // some code here to fill cells
  console.log('exporting component');
  this._excelExportService.exportAsExcelFile(cells, 'global_view');
}

The service call by the export() function is :

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

const EXCEL_TYPE = 'application/vnd.openxmlformats- officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';

@Injectable()
export class ExcelExportService {

constructor() { }

public exportAsExcelFile(json: any[], excelFileName: string, header?: any): void {
  const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
  const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  const excelBuffer: any =
    XLSX.writeFile(
      workbook,
      excelFileName + '_export_' + Date.now() + EXCEL_EXTENSION,
      { bookType: 'xlsx', bookSST: false, type: 'buffer' }
  );
}
}

When I click the button, the export() function is called twice, ans so I get two different excel files, and two console.log(). But if I just comment :

export() {
  let cells = [];
  // some code here to fill cells
  console.log('exporting component');
  // this._excelExportService.exportAsExcelFile(cells, 'global_view');
}

the function is called just once, as expected.

Why the call to my service is changing the behavior on my function ?

Upvotes: 3

Views: 5076

Answers (1)

Melchia
Melchia

Reputation: 24224

You need to use (click)="export()". Refer to documentation

<dx-button text="{{'VIEW_DATA.BUTTON.EXPORT_TO_EXCEL' | translate }}" type="normal" (click)="export()" ></dx-button>

Upvotes: 2

Related Questions