cnico
cnico

Reputation: 23

Angular store pop removed item to add back in sequential order

I have been trying to remove and add items in sequential order out of an array. it seems pop removes the item form the array, not allowing it to be returned back into the array for display at a later time. This code uses the the Add and Remove Columns from the Angular 8 website examples.

I have tried setting ++, -- on items, etc. I am sure it is easy to do, I just cant get it. With the way the code is current setup, it removes a column fine, just putting it back comes up as undefined due to pop destroying it? It is current setup as adding a random column, which i do not want.

import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { TestService } from '../json.service';

export interface DataTable {
  Id: number;
  Name: string;
  Phone: number;
  Email: string;
  Company: string;
  City: string;
  Url: string;
}

@Component({
  selector: 'app-data-table',
  styleUrls: ['data-table.component.css'],
  templateUrl: 'data-table.component.html',
})

export class DataTableComponent implements AfterViewInit {
constructor(private svc: TestService, private http: HttpClient) {
 /* this.svc.printToConsole('HttpClient services are running');*/
}
@ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
@ViewChild(MatSort, {static: false}) sort: MatSort;

  DataTable: string [];
  displayedColumns: string[] = ['Id', 'Name', 'Phone', 'Email', 'Company', 'City', 'Url'];
  columnsToDisplay: string[] = this.displayedColumns.slice();
  dataSource = new MatTableDataSource(this.DataTable);

  ngAfterViewInit() {
    this.http.get('./assets/data/sampledata.json').subscribe(
      data => {
        this.DataTable = data as string [];
        this.dataSource.data = this.DataTable;
        this.dataSource.sort = this.sort;
        this.dataSource.paginator = this.paginator;
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }

  addColumn() {
    if (this.columnsToDisplay.length < 7) {
    const randomColumn = Math.floor(Math.random() * this.displayedColumns.length);
    this.columnsToDisplay.push(this.displayedColumns[randomColumn]);
  }
}

  removeColumn() {
    if (this.columnsToDisplay.length > 3) {
      this.columnsToDisplay.pop();
    }
  }

  shuffle() {
    let currentIndex = this.columnsToDisplay.length;
    while (0 !== currentIndex) {
      const randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // Swap
      const temp = this.columnsToDisplay[currentIndex];
      this.columnsToDisplay[currentIndex] = this.columnsToDisplay[randomIndex];
      this.columnsToDisplay[randomIndex] = temp;
    }
  }
}




<div class="ng-container">
    <button mat-raised-button (click)="addColumn()"> Add Column </button>
    <button mat-raised-button (click)="removeColumn()"> Remove Column </button>
    <button mat-raised-button (click)="shuffle()"> Shuffle </button>
<table mat-table [dataSource]="dataSource" matSort  class="mat-elevation-z8">
          <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
              <th mat-header-cell *matHeaderCellDef mat-sort-header> {{column}} </th>
              <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
            </ng-container>
    <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
  </table>
  <mat-paginator [length]="30"
  [pageSize]="5"
  [pageSizeOptions]="[5, 10, 20, 30]" showFirstLastButtons>
</mat-paginator>
</div>

I need for the add column to add up to 7 original items max in sequential array order left to right, and remove in the order down to 3 columns min from right to left.

Upvotes: 1

Views: 200

Answers (1)

Simon K
Simon K

Reputation: 2857

If I'm understanding your problem right, you just want to be able to pop items off of the array and then push them back on later in the reverse order they were popped?

Easiest thing to do here is to just store the values that you are popping off:

poppedItems: string[] = [];

removeColumn() {
    if (this.columnsToDisplay.length > 3) {
        this.poppedItems.push(this.columnsToDisplay.pop());
    }
}

addColumn() {
    if (this.columnsToDisplay.length < 7) {
        this.columnsToDisplay.push(this.poppedItems.pop());
    }
}

Upvotes: 1

Related Questions