import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import * as moment from 'moment'; import { TaxReportDatasource } from './tax-report-datasource'; import { TaxReport } from './tax-report'; import { ToCsvService } from '../shared/to-csv.service'; @Component({ selector: 'app-tax-report', templateUrl: './tax-report.component.html', styleUrls: ['./tax-report.component.css'] }) export class TaxReportComponent implements OnInit { dataSource: TaxReportDatasource; form: FormGroup; info: TaxReport; /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */ displayedColumns = ['name', 'taxRate', 'saleAmount', 'taxAmount']; constructor( private route: ActivatedRoute, private router: Router, private fb: FormBuilder, private toCsv: ToCsvService ) { this.createForm(); } ngOnInit() { this.route.data .subscribe((data: { info: TaxReport }) => { this.info = data.info; this.form.setValue({ startDate: moment(this.info.startDate, 'DD-MMM-YYYY').toDate(), finishDate: moment(this.info.finishDate, 'DD-MMM-YYYY').toDate() }); this.dataSource = new TaxReportDatasource(this.info.amounts); }); } show() { const info = this.getInfo(); this.router.navigate(['tax-report'], { queryParams: { startDate: info.startDate, finishDate: info.finishDate } }); } createForm() { this.form = this.fb.group({ startDate: '', finishDate: '' }); } getInfo(): TaxReport { const formModel = this.form.value; return { startDate: moment(formModel.startDate).format('DD-MMM-YYYY'), finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY') }; } exportCsv() { const headers = { Name: 'name', Amount: 'amount' }; const csvData = new Blob([this.toCsv.toCsv(headers, this.dataSource.data)], {type: 'text/csv;charset=utf-8;'}); const link = document.createElement('a'); link.href = window.URL.createObjectURL(csvData); link.setAttribute('download', 'tax-report.csv'); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }