How can I output data from the clipboard in a FormArray in a table?

264 views Asked by At

My goal is to copy values from Excel and output them in an HTML table in the exact order.

Excel dummy is structured as follows: enter image description here

Test-Data

https://easyupload.io/xb2soz

For this I have already implemented the following code:

// HTML
...
<label>
  <input style="background-color: silver" type="text 
        [formControl]="rowControl.get(column.attribute)"
        (paste)="pasteExcelData($event)" // Use here the paste event />
</label>
...
// TS
/**
   * Paste excel data into data table
   */
  pasteExcelData(event: ClipboardEvent) {
    // Get the clipboard text
    const clipboardText = event.clipboardData.getData('text');

    // Split into rows
    let clipRowsArray = [];
    clipRowsArray = clipboardText.split(String.fromCharCode(13));
    console.log('Split into rows:', clipRowsArray);

    // Split rows into columns
    for (let i = 0; i < clipRowsArray.length; i++) {
      clipRowsArray[i] = clipRowsArray[i].split(String.fromCharCode(9));
    }
    console.log('Split rows into columns:', clipRowsArray);

    // Write out in data table
    for (let index = 1; index < 7; index++) {
      const month = `${index}`;
      // TODO
    }
  }

Im already able to copy the values from excel and when pasting the values output correctly in the browser console in the array.

See here: enter image description here

The problem is that all the values are only inserted into one input. How can I distribute the values from the clipboard array to the respective FormControls of the FormArray? Can you please help me with this?

I have also created a Stackblitz here for my work: https://stackblitz.com/edit/angular-wmfjhh-qnro6f?file=app%2Ftable-basic-example.ts,app%2Ftable-basic-example.html,main.ts,app%2Ftable-basic-example.css

1

There are 1 answers

0
traynor On

Since it's nested form array, you might use a nested loop, to get each row, and then get its each control, and insert data into each control with patchValue, which corresponds the clipboard array:

try this:

for (let ind = 0; ind < clipRowsArray.length; ind++) {
  
  for (let index = 1; index < 7; index++) {

    const month = `${index}`;
    this.rows.controls[ind].controls[month].patchValue(clipRowsArray[ind][month-1]);
    
  }
}

Also, not sure why, patchValuedidn't work for the input field which receives the data, it would hold the input data, but adding blur on paste event seem to work:

#inp

(paste)="pasteExcelData($event); inp.blur()" 

stackblitz