Home » Javascript » javascript – store table data in array of objects

javascript – store table data in array of objects

Posted by: admin February 24, 2020 Leave a comment

Questions:

I just started with angular. I have a table and I need to store table data in the form of an array of objects as I shown below.onclick on some button(in my case it is generate button) I need to store table data. I tried searching online but I didn’t get enough resources to figure out the way to do it. I am giving stackblitz link below. thanks in advance.

tableData = [{row1 data},
             {row2 data},
             {row3 data},
               ......  ]

stackblitz link

How to&Answers:

You can achieve this using angular dynamic reactive form

HTML:

<div class="container-fluid">
  <h3>
    <b>Create Test in 3 Steps</b>
  </h3>

  <form [formGroup]="form" ngNativeValidate>
    <table class="table table-hover">
      <thead>
        <tr>
          <th>No. of Questions</th>
          <th>Subject</th>
          <th>Category</th>
          <th>Topic</th>
          <th>Solution Type</th>
          <th>Question Type</th>
          <th>Marks</th>
          <th>Negative Marking</th>
          <th>Difficulty</th>
      </tr>
      </thead>

      <tbody  class="form-group" formArrayName="items">
        <tr *ngFor="let row of form.get('items').controls; let i = index" [formGroupName]="i">
            <td class="col-md-1">    
              <input type="number" formControlName="questions" class="form-control" name="questions" value="0"> 
            </td>
            <td>
              <select class="form-control" name="subjects" formControlName="subjects">

                <option [value]="" disabled selected>Select</option>
                <option *ngFor="let map of subject_maps" [value]="map._id" [selected]="map == subject_map">
                  {{ map.subject_node.fullform }}</option>
              </select>
            </td>
            <td>
              <select  class="form-control" name="category" formControlName="category">
                <option [value]="" disabled selected>Select</option>
                <option *ngFor="let cn of subject_maps?.subject_node?.category_nodes" [value]="cn._id" [selected]="cn._id == selected_category?._id">
                  {{ cn.fullform }}</option>
              </select>
            </td>
            <td>
              <select class="form-control" name="topics" formControlName="topics">
                <option [value]="" disabled selected>Select</option>
                <option *ngFor="let tn of selected_category?.topic_nodes" [value]="tn._id" [selected]="tn._id == selected_topic?._id">
                  {{ tn.fullform }}</option>
              </select>
            </td>
            <td>
              <select  class="form-control" name="solutionT" formControlName="solutionT">
                <option value="knowledge" selected>Knowledge</option>
                <option value="formula">Formula</option>
              </select>
            </td>
            <td>
              <select class="form-control"  name="questionT" formControlName="questionT">
                <option value="mcq" selected>MCQ</option>
                <option value="msq">MSQ</option>
                <option value="numerical">Numerical</option>
              </select>
            </td>
            <td class="col-md-1">
              <input type="number" formControlaName="marks" class="form-control" name="marks" value="1" > 
            </td>
            <td class="col-md-1">
              <input type="number" class="form-control" name="Nmarks" value="0" formControlaName="Nmarks"> 
            </td>
            <td>
              <select class="form-control" name="difficulty" formControlaName="difficulty">
                <option value="easy" selected>Easy</option>
                <option value="medium">Medium</option>
                <option value="hard">Hard</option>
              </select>
            </td>
            <td>
              <button class="btn btn-danger" (click)="deleteRow(i)">Delete</button>
            </td>
        </tr>
      </tbody>
    </table>
    <div class="text-center">       
       <button class="btn btn-primary" (click)="addItem()">ADD more rows</button>
    </div>
  </form>
<div class="container">
<div class="pull-right generate_button">
  <button class="btn btn-danger" (click)="create()">Generate</button>
</div>
</div>  
</div>

TS:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular';
  form: FormGroup;
  items: FormArray;
  constructor(private fb : FormBuilder) {}
  ngOnInit () {
    this.form = this.fb.group({
        items: new FormArray([this.createItem()])
      })
  }
  createItem(): FormGroup {
    return this.fb.group({
        questions: '',
        subjects: '',
        category: '',
        topics: '',
        solutionT: '',
        questionT: '',
        marks: '',
        Nmarks: '',
        difficulty: ''
    });
  }
  addItem(): void {
    this.items = this.form.get('items') as FormArray;
    this.items.push(this.createItem());
    console.log(this.form.get('items').value);
  }
  deleteRow(index: number) {
    this.items.removeAt(index);
  }
}

Stackblitz link for reference :- https://stackblitz.com/edit/angular-j3jw7q?file=src%2Fapp%2Fapp.component.ts

Answer:

write your add button template like this:
create an object of inputs and then add id property that has index as value, then send this object to be add to rows array.

  <button class="btn btn-primary" (click)="addrows({id:rows.length})">ADD more rows</button>


<button class="btn btn-danger" (click)="deleterow(i)">Delete</button>

Create a row array like below:

row:any[]=[];

Then write your add method:

  addrows(row) {
    this.rows.push(row);
  }

Your delete row must be like this:

deleterow(id) {
    this.rows.splice(
      rows.indexOf(a => a.id=== id),
      1,
    );
  }