import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { ProductListDataSource } from './product-list-datasource'; import { Product } from '../../core/product'; import { ActivatedRoute } from '@angular/router'; import { debounceTime, distinctUntilChanged, startWith } from 'rxjs/operators'; import { FormBuilder, FormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { ToCsvService } from '../../shared/to-csv.service'; @Component({ selector: 'app-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'] }) export class ProductListComponent implements OnInit, AfterViewInit { constructor(private route: ActivatedRoute, private fb: FormBuilder, private toCsv: ToCsvService) { this.showExtended = false; this.createForm(); this.filter = this.listenToFilterChange(); } get showExtended(): boolean { return this._showExtended; } set showExtended(value: boolean) { this._showExtended = value; if (value) { this.displayedColumns = ['name', 'costPrice', 'productYield', 'productGroup', 'info']; } else { this.displayedColumns = ['name', 'costPrice', 'productGroup', 'info']; } } @ViewChild('filterElement', { static: true }) filterElement: ElementRef; @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator; @ViewChild(MatSort, { static: true }) sort: MatSort; dataSource: ProductListDataSource; filter: Observable; form: FormGroup; list: Product[]; /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */ displayedColumns: string[]; private _showExtended: boolean; createForm() { this.form = this.fb.group({ filter: '' }); } listenToFilterChange() { return this.form.get('filter').valueChanges .pipe( startWith(''), debounceTime(150), distinctUntilChanged() ); } ngOnInit() { this.route.data .subscribe((data: { list: Product[] }) => { this.list = data.list; }); this.dataSource = new ProductListDataSource(this.paginator, this.sort, this.filter, this.list); } ngAfterViewInit() { setTimeout(() => { this.filterElement.nativeElement.focus(); }, 0); } exportCsv() { const headers = { Code: 'code', Name: 'name', Units: 'units', Fraction: 'fraction', FractionUnits: 'fractionUnits', CostPrice: 'costPrice', Yield: 'yield', ProductGroup: 'productGroup' }; 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', 'products.csv'); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }