0

I am using Angular 9 and using material table. I want to have a button which can copy the content of the table to the ClipBoard. I have tried using [cdkCopyToClipboard] and bind it to the dataSource but when I copy , the result I get is [object Object]. Can somebody help me here ?

app.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';

export interface UserData {
  id: string;
  name: string;
  progress: string;
  color: string;
}

/** Constants used to fill up our data base. */
const COLORS: string[] = [
  'maroon', 'red', 'orange', 'yellow', 'olive', 'green', 'purple', 'fuchsia', 'lime', 'teal',
  'aqua', 'blue', 'navy', 'black', 'gray'
];
const NAMES: string[] = [
  'Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack', 'Charlotte', 'Theodore', 'Isla', 'Oliver',
  'Isabella', 'Jasper', 'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth'
];

/**
 * @title Data table with sorting, pagination, and filtering.
 */
@Component({
  selector: 'table-overview-example',
  styleUrls: ['table-overview-example.css'],
  templateUrl: 'table-overview-example.html',
})
export class TableOverviewExample implements OnInit {
  displayedColumns: string[] = ['name'];
  dataSource: MatTableDataSource<UserData>;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;

  constructor() {
    // Create 100 users
    const users = Array.from({length: 100}, (_, k) => createNewUser(k + 1));

    // Assign the data to the data source for the table to render
    this.dataSource = new MatTableDataSource(users);
  }

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}

/** Builds and returns a new User. */
function createNewUser(id: number): UserData {
  const name = NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' +
      NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.';

  return {
    id: id.toString(),
    name: name,
    progress: Math.round(Math.random() * 100).toString(),
    color: COLORS[Math.round(Math.random() * (COLORS.length - 1))]
  };
}

app.component.html

<mat-form-field>
  <mat-label>Filter</mat-label>
  <input matInput (keyup)="applyFilter($event)" placeholder="Ex. Mia">
</mat-form-field>

<div class="mat-elevation-z8">
      <button [cdkCopyToClipboard]="dataSource">Click to Copy</button>

  <table mat-table [dataSource]="dataSource" matSort>
    

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
      <td mat-cell *matCellDef="let row"> {{row.name}} </td>
    </ng-container>


    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;">
    </tr>
  </table>

  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

As you can see in the html file, which lets you copy the content but somehow it's not working with MatTableDataSource. Thanks in advance.

Saurav Ahlawat
  • 81
  • 1
  • 4
  • 9

1 Answers1

1

You need to change object to JSON.

1st method:

Add following to app.component.ts in constructor()

const copiedData = JSON.stringify(this.datasource.data);

and change this:

 <button [cdkCopyToClipboard]="dataSource">Click to Copy</button>

to this:

 <button [cdkCopyToClipboard]="copiedData">Click to Copy</button>

2nd method:

Create a new function in app.component.ts

 copyData() {
    return JSON.stringify(this.dataSource.data);
  }

and use:

 <button [cdkCopyToClipboard]="copyData()">Click to Copy</button>

If you want the copied data to be just the values of object.

In this example I am assuming that your table will have more than one column.

A simple example is following:

  copyData() {
    let data = "";
    this.dataSource.data.forEach(row => {
      data += this.ObjectToArray(row)
    })
    return data;
  }

  ObjectToString(obj: Object): string {
    // If you are using ES8 you can use const result = Object.values(obj);
    // else use the code give below
    let result = Object.keys(obj).map((key: keyof typeof obj) => {
      let value = obj[key];
      return value;
    });

    // then return the result as string along with a new line
    result.toString() + "\n";
  }

Here is a working example in stackblitz.

isAif
  • 2,126
  • 5
  • 22
  • 34
  • This indeed copies the data, but It has slight problem, one that I do not know how to solve. If I do this, I get the entire array, including all key value pairs, something like `[{"name":"Saurav"},{"name":"Andrew"},{"name":"John"}]`. But I want just `Saurav,Andrew ,John` to be copied to the clipboard. Any idea on how I can do that ? – Saurav Ahlawat Jun 20 '20 at 17:19
  • Also one suggestion, `JSON.stringify(this.dataSource)` gives converting circular structure to JSON error, I had to do `JSON.stringify(this.dataSource.data)` to make it work. You might want to edit that in your answer. – Saurav Ahlawat Jun 20 '20 at 17:22
  • As a result I have JSON. But how to get html wich can be pasted in spreadsheet? – Marcin Żmigrodzki Jul 29 '21 at 10:08
  • @Marcin I think you need to convert it to csv not html. You can search for "json to csv conversion". You will need some package for that. – isAif Jul 29 '21 at 10:27