Creating a JSON array or JSON object from an Angular Material table

My task is to create a JSON array or object from an Angular Material table, which I can then utilize to export to an Excel sheet.

Here is the data:

const ELEMENT_DATA: Element[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
  {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
  {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
  {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
  {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
  {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
  {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
  {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
  {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
  {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'},
];

Below is the Material table:

<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">

    <!-- Position Column -->
    <ng-container matColumnDef="position">
      <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
    </ng-container>

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

    <!-- Weight Column -->
    <ng-container matColumnDef="weight">
      <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.weight}} </mat-cell>
    </ng-container>

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.symbol}} </mat-cell>
    </ng-container>

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

The goal is to generate a JSON object of this Material table.

Answer №1

If you're looking to retrieve an excel sheet, you can simply download it directly from the ELEMENT_DATA instead of going through the material table.

ts file

const Element=[  
{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}
];
DownloadAsExcel()
{
const worksheet: XLSX.WorkSheet=XLSX.utils.table_to_sheet(this.table.nativeElement);
const tbltojson = (JSON.parse(JSON.stringify(worksheet)));
const workbook: XLSX.WorkbBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');  //can use 'tbltojson' instead of 'worksheet' to download excel from a JSON object. Both work similarly
/* save to file */
XLSX.writeFile(workbook, 'YourFileName.xlsx');
}

Preview of the downloaded excel file: also ensure to import the xlsx module to prevent any errors in the code execution.

Alternatively, if you require a json object, you can convert the ELEMENT_DATA into a json form as shown below:

JSON.parse(JSON.stringify(Element));

the JSON representation:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to automatically fetch all pages from a REST API request without having to explicitly state the page number each time?

When working with a paginated API to fetch data and convert it into .JSON format, I am looking for a way to retrieve all the pages in the response without explicitly specifying page numbers in the URL. The API allows inputs for page number and results per ...

Monitoring changes within the browser width with Angular 2 to automatically refresh the model

One of the challenges I faced in my Angular 2 application was implementing responsive design by adjusting styles based on browser window width. Below is a snippet of SCSS code showing how I achieved this: .content{ /*styles for narrow screens*/ @m ...

Error encountered when trying to parse a URL containing Arabic characters

I've been attempting to use a web service to translate Arabic text to English, but I keep encountering an error while constructing the URL. I have defined two possible cases for errors: enum MyErrors: Error { case urlParsingError(String) case ...

Guide to creating a unit test for canActivate guard in Angular routing

Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation. app-routing.mod ...

What is preventing access to the JSON data?

function loadResponse(filter) { $.ajax({ type: 'GET', url: 'path/to/example.json', dataType: 'json', cache: false, beforeSend: function () { console.log('load ...

Can a React.tsx project be developed as a standalone application?

As a student, I have a question to ask. My school project involves creating a program that performs specific tasks related to boats. We are all most comfortable with React.tsx as the programming language, but we are unsure if it is possible to create a st ...

Angular: Designing personalized hyperlink overlays for text content with a filter

Currently, I am dealing with a json feed that provides information about cars. A portion of the text includes [VIN:'vin_number_is_here']Car make model here[/VIN]. To display this in an ng-repeat loop, I would like to use a filter to process the t ...

Creating a generic array type in TypeScript that includes objects with every key of a specified interface

I am working with an interface called Item interface Item { location: string; description: string; } Additionally, I have a generic Field interface interface Field<T extends object> { name: keyof T; label: string; } I want to create an Arra ...

Discovering JSON data in Angular 4

I am working with a JSON data format retrieved from (this.url) { "user": [ { "id": "1", "name": "root", "password": "root" }, { "id": "2", "name": "clienttest", ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

Can TypeScript be set up to include undefined as a potential type in optional chains?

Today, I encountered a bug that I believe should have been caught by the type system. Let me illustrate with an example: function getModel(): Model { /* ... */ } function processModelName(name: string) { return name.replace('x', 'y& ...

Generate a dynamic key object in Angular/TypeScript

I am working with an object called "config" and an id named "id". My goal is to create an array of objects structured like this: [ "id" : { "config1: ... "config2: ... "config3: ... } "id2" : { "config ...

Steps for excluding a file from compilation during angular testingExclude a file from being

I have a dilemma with my Angular 7 application that I built using the angular cli. During the ng-test process, I need a specific file to be excluded from compilation. The file causing issues is "app/config/context.prod.ts" To rectify this, I included th ...

Choose historical dates with the dl-date-time-picker component within an Angular application

In my Angular 7 project, I have integrated a datetimepicker component called dl-date-time-picker. I want to prevent users from selecting previous dates in the date and time picker. Although I tried using the [selectFilter] attribute for this purpose, it en ...

Checking dynamically if a key-value pair exists in a JSON object

Here is some information that I have: "Vitals":[ { "Bp Systolic":"", "Bp Diastolic":"", "Weight":"", "Height":"", "BMI":"" } ], "Lab":[ { "Lipid_profile":[{ "Total Cholestrol":"", "TRIGLYCERID ...

Develop a simulated version that does not include all the functionalities of the primary service

Let's imagine a scenario where there is an OriginalService class with various methods class OriginalService { method1() { } method2() { } method3() { } .. } Now, suppose we need to create a mock of OriginalService that will only be used with ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

Updating events instantly with a single click in Angular 6: A step-by-step guide

Hello there, I am currently diving into learning Angular 6 and I have encountered a query. I want to achieve a functionality where upon clicking a button, the text on the button changes as well as the corresponding event that triggers when the button is cl ...

In TypeScript, values other than numbers or strings can be accepted as parameters, even when the expected type is a

The issue I am encountering with TypeScript is quite perplexing, especially since I am new to this language and framework. Coming from a Java background, I have never faced such a problem before and it's presenting challenges in my bug-fixing efforts ...