'Angular PrimeNG Table not loading properly

Angular PrimeNG table not loading properly

I am working with an existing Angular PrimeNG table that is not loading properly. The data is loading properly from the http service in the table. However, the table is not functioning properly. The inline editing functionality is not working, buttons not loading on right, row selection is selecting every row, and the table is not pretty. Please let me know if you have any ideas.

carriers.component.html

    <h1>Carriers</h1>
<div class="col-12 grid">
  <p-table #dt class="carriers-table" [value]="carriers" [paginator]="true" [rows]="5" [(selection)]="selectedCarriers"  dataKey="stgCarriersId"
  [totalRecords]="totalRecords" [loading]="loading" [lazy]="true" (onLazyLoad)="loadCarriersLazy($event)">
  <ng-template pTemplate="header">
        <tr>
          <!-- The first position is holding for Select All checkbox, we can add it if needed in the future -->
          <th></th>
          <th *ngFor="let col of cols">
            {{col.header}}
          </th>
          <th style="width:8em"></th>
        </tr>
        <tr class="filter-row">
          <!-- The first position is holding for Select All checkbox-->
          <th></th>
          <th *ngFor="let col of cols" id="{{col.field}}">        
            <input *ngIf="col['filter'] && col['filterType'] === 'input'" pInputText type="text"
              (input)="dt.filter($event.target.value, col.field, 'contains')">
            <p-dropdown *ngIf="col['filter'] && col['filterType'] === 'dropdown'" [options]="col['options']"
              (onChange)="dt.filter($event.value, col.field, 'equals')"></p-dropdown>
          </th>
          <th style="width:8em"></th>
        </tr>
      </ng-template>
      <ng-template pTemplate="body" let-rowData>
        <tr [pSelectableRow]="rowData" [pEditableRow]="rowData">
          <td>
            <p-tableCheckbox [value]="rowData"></p-tableCheckbox>
          </td>
          <td *ngFor="let col of cols">
            <div [ngSwitch]="rowData.editing && col.editable && formReady">
              <div *ngSwitchCase="true">
                <midas-input [type]="col.type" [options]="col.options"
                  [control]="getControl(form, 'stagedCarriers.' + col.field)"></midas-input>
              </div>
              <div *ngSwitchDefault>
                <div [ngSwitch]="col.field">
                  <div *ngSwitchCase="'stgdocFileNm'">
                    {{rowData.stgCarrierFileNm ? rowData.stgCarrierFileNm : carrierTypeMap.get(rowData.stgCarrierTyp)}}
                  </div>
                  <div *ngSwitchDefault>
                    {{col.type === 'DATE' ? (rowData[col.field] | date : "short") : rowData[col.field]}}
                  </div>
                </div>
              </div>
            </div>
          </td>
          <td style="text-align:center; display: flex; align-items: center; display: table-cell">
            <button *ngIf="!rowData.editing" pButton type="button" pSaveEditableRow icon="pi pi-envelope"
              class="ui-button-info" style="margin-right: .5em" (click)="emailDoc(rowData)"></button>
            <button *ngIf="!rowData.editing" pButton type="button" pInitEditableRow icon="pi pi-pencil"
              class="ui-button-info" (click)="onRowEditInit(rowData)" [ngClass]="{ 'disabled-button': editing }"
              [disabled]="editing"></button>
            <button *ngIf="rowData.editing && formReady" pButton type="button" pSaveEditableRow icon="pi pi-check"
              class="ui-button-success" style="margin-right: .5em" (click)="onRowEditSave(rowData)"></button>
            <p-progressSpinner *ngIf="rowData.editing && !formReady"
              [style]="{'margin-right': '.5em', width: '30px', height: '30px'}">
            </p-progressSpinner>
            <button *ngIf="rowData.editing" pButton type="button" pCancelEditableRow icon="pi pi-times"
              class="ui-button-danger" (click)="onRowEditCancel(rowData)"></button>
          </td>
        </tr>
      </ng-template>
    </p-table>
  
    <par-doc-upload *ngIf="!!txSet" style="width: 100%;" multiple="true" [docTypes]="docTypes" [erErId]="erErId"
      (uploadDocEvent)="uploadDocEvent($event)" [isDocsScreen]="isDocsScreen" [txSet]="txSet">
    </par-doc-upload>
  </div>
  <div class="button-container sticky">
    <button class="back-button primary-button-blue" (click)="goToMenu()">
      <i class="pi pi-angle-left"></i>
      Back to Main Menu
    </button>
    <button class="hidden-buton tertiary-button" style="pointer-events: none;"></button>
    <button class="primary-button" (click)="emailAll()"
      >Add</button>
    <button class="primary-button" (click)="downloadDocs()"
     >Download</button>
  </div>
  <p-dialog [(visible)]="display" [style]="{'width': '50%'}" [closable]="false">
    <par-email-component *ngIf="fileEmail" [initialEmail]="fileEmail" (onEmailSend)="onEmailSend($event)">
    </par-email-component>
  </p-dialog>
  <p-toast></p-toast>

carriers.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { merge } from 'lodash';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { SelectItem, LazyLoadEvent, MenuItem } from 'primeng/api';
import { Action } from 'libraries/eb-shared/src/lib/transaction/action';
import { TransactionService } from 'libraries/eb-shared/src/lib/transaction/transaction.service';
import { Transaction } from 'libraries/eb-shared/src/lib/transaction/transaction';
import { MessageHelperService } from 'libraries/eb-shared/src/lib/components/message/message-helper.service';
import { AuthService } from 'libraries/eb-shared/src/lib/auth/auth.service';
import { TransactionSet } from 'libraries/eb-shared/src/lib/transaction/transaction-set';
import { Page } from 'src/models/page';
import { RestService } from 'libraries/eb-shared/src/lib/http/rest.service';
import { API_BASE_PATHS } from 'libraries/eb-shared/src/lib/http/api-base-paths.enum';
import { Carriers } from 'src/models/v2/carriers';
import { FormComponent } from '../../shared/form/form.component';
import { CarriersTransaction } from './carriers-transaction';
import { MidasTransactionService } from '../../shared/utils/midas-transaction.service';
import { StagedCarriers } from 'src/models/v2/staged-carriers';

@Component({
  selector: 'midas-carriers',
  templateUrl: './carriers.component.html',
  styleUrls: ['./carriers.component.less']
})
export class CarriersComponent extends FormComponent<CarriersTransaction> implements OnInit {

  params: Map<any, any>;
  erErId: number;

  txSet: TransactionSet<any, any>;

  midasOptions: SelectItem[] = [
    { label: 'Select', value: null },
    { label: 'Y', value: 'Y' },
    { label: 'N', value: 'N' }
  ];

  carriers: StagedCarriers[] = [];
  selectedCarriers: StagedCarriers[] = [];
  transaction: Transaction<CarriersTransaction>;
  totalRecords = 0;
  loading = false;
  editing = false;
  display = false;

  cols = [
    { header: 'Code', field: 'carrCarrierCd', type: 'TEXT' },
    { header: 'Name', field: 'carrCarrierNm', type: 'TEXT' },
    { header: 'First Name', field: 'carrCntctFstNm', type: 'TEXT' },
    { header: 'Last Name', field: 'carrCntctLstNm', type: 'TEXT' },
    { header: 'Phone Number', field: 'carrCntctPhoneNo', type: 'TEXT' },
    { header: 'Ext No', field: 'carrCntctExtNo', type: 'TEXT' },
    { header: 'Email', field: 'carrCntctEmail', type: 'TEXT' },
    { header: 'URL', field: 'carrCarrierUrl', type: 'TEXT' },
    { header: 'Created', field: 'carrInitCrtdDt', type: 'DATE' },
    { header: 'Last Updated', field: 'carrLstUpdtDt', type: 'DATE' },
    { header: 'Updated By', field: 'carrLstUpdtByUserId', type: 'TEXT' },

  ];

  constructor(
    private authService: AuthService,
    private route: ActivatedRoute,
    private router: Router,
    private messageService: MessageHelperService,
    private restService: RestService,

    public transactionService: TransactionService,
    public txService: MidasTransactionService
  ) {
    super(txService);
  }

  items: MenuItem[];

  activeItem: MenuItem;

  ngOnInit() {
    this.getControls('StagedCarriers', 'stagedCarrierTransaction');
    this.restService.get<Page<StagedCarriers>>('planV2', 'carriers',
      {
      }).subscribe(res => {
        console.log(res);
        if (res && res.content) {
          this.carriers = res.content;
          this.totalRecords = res.totalElements;
        } else {
          this.carriers = [];
        }
      });

  }

  loadCarriersLazy(event: LazyLoadEvent) {
    const pageNum = event.first / event.rows;
    const size = 5;
    this.loading = true;
    const params = merge({
      stgdocErId: this.erErId,
      page: pageNum,
      size: size,
      midasDisplayInd: 'midas',
      sort: 'carrInitCrtdDt,DESC'
    }, this.buildParams(event));

    this.restService
      .get<Page<StagedCarriers>>('planV2', 'carriers', params)
      .subscribe(res => {
        this.loading = false;
        if (res && res.content) {
          this.carriers = res.content;
          this.totalRecords = res.totalElements;
        }else{
          this.carriers = [];
        }
      },
      errRes => {
        this.loading = false;
        console.log(errRes);
        this.messageService.httpErrorResponse(errRes);
      });
  }

  private buildParams(event: LazyLoadEvent): { [key: string]: any } {
    if (event && event.filters) {
      const params = {};
      Object.keys(event.filters).forEach(property => {
        params[property] = event.filters[property].value.toLowerCase();
      });
      return params;
    }
    return {};
  }

  resetForm() {
    this.editing = false;
    this.form = undefined;
    this.formReady = false;
  }

  onRowEditCancel(doc: StagedCarriers) {
    doc['editing'] = false;
    this.resetForm();
  }

  onRowEditInit(doc: StagedCarriers) {
    this.editing = true;
    doc['editing'] = true;
    const index = { stgCarriersId: doc.stgCarriersId };
    this.transactionService
      .view<CarriersTransaction>(
        'StagedCarriers',
        Action.update,
        //TODO: Uncomment the line below 
        // index, 
        null,
        null,
        'planV2'
      )
      .subscribe(
        res => {
          this.transaction = res;
          this.entity = res.submit;
          console.log(this.entity);
          this.buildForm();
        },
        err => {
          this.messageService.httpErrorResponse(err);
          this.onRowEditCancel(doc);
        }
      );
  }

  goToMenu() {
    this.router.navigate(['/']);
  }

  

}

carriers.component.less

par-input {
    margin: 0px;
}

::ng-deep .p-dropdown {
    min-width: 2.5em;
}


::ng-deep p-table.carriers-table .p-datatable{
    tr{
        &.p-highlight {
            
        }
        td{word-wrap: break-word;}
    }
}

.button-container{
    .back-button{position: relative; background: transparent; color: #1809ca; padding: 0 20px; margin-right: 20px;
        i{font-size: 26px; -webkit-text-stroke: 1px #fff;}
        &:after{content: ''; width: 1px; height: 85%; background: #d1cdf2; position: absolute; top: 3px; right: -6px;}
        &:hover{color: darken(#1809ca, 20%); cursor: pointer;}
    }
    .next-button{position: relative; background: transparent; color: #1809ca; padding: 0 20px; margin-left: 20px;
        i{font-size: 26px; -webkit-text-stroke: 1px #fff;}
        &:after{content: ''; width: 1px; height: 85%; background: #d1cdf2; position: absolute; top: 3px; left: -6px;}
        &:hover{color: darken(#1809ca, 20%); cursor: pointer;}
    }
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source