How to reset the width of custom-sized table columns in a prime-ng p-table

Is there a method to reset the column widths of a p-table in primeng that have been set with 'resizableColumns="true"'? I want to provide users with the ability to revert back to the original sizes.

Answer №1

To resolve the issue, try revalidating your table.

Check out this example

HTML

<p-table #dt [columns]="cols" [value]="cars1" [resizableColumns]="isResisable" [loading]="isLoading" *ngIf="!isLoading" >
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns" pResizableColumn>
                {{col.header}}
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <td *ngFor="let col of columns" class="ui-resizable-column">
                {{rowData[col.field]}}
            </td>
        </tr>
    </ng-template>
</p-table>

<button (click)="resettable()" >Reset Initial </button>

TS

import { Component, OnInit, ViewChild } from '@angular/core';

import { LazyLoadEvent, DataTable } from 'primeng/primeng';

import { CarService } from './app.service'
import { Car } from './car.model'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @ViewChild('dt') public dataTable: DataTable;

  cars1: Car[];

  isResisable: boolean = true;;

  cols: any[];
  isLoading: boolean;
  constructor(private carService: CarService) { }

  ngOnInit() {

    this.cars1 =
      [
        { "brand": "VW", "year": 2012, "color": "Orange", "vin": "dsad231ff" },
        { "brand": "Audi", "year": 2011, "color": "Black", "vin": "gwregre345" },
        { "brand": "Renault", "year": 2005, "color": "Gray", "vin": "h354htr" },
        { "brand": "BMW", "year": 2003, "color": "Blue", "vin": "j6w54qgh" },
        { "brand": "Mercedes", "year": 1995, "color": "Orange", "vin": "hrtwy34" },
        { "brand": "Volvo", "year": 2005, "color": "Black", "vin": "jejtyj" },
        { "brand": "Honda", "year": 2012, "color": "Yellow", "vin": "g43gr" },
        { "brand": "Jaguar", "year": 2013, "color": "Orange", "vin": "greg34" },
        { "brand": "Ford", "year": 2000, "color": "Black", "vin": "h54hw5" },
        { "brand": "Fiat", "year": 2013, "color": "Red", "vin": "245t2s" }
      ]


    this.cols = [
      { field: 'vin', header: 'Vin', width: '25%' },
      { field: 'year', header: 'Year', width: '15%' },
      { field: 'brand', header: 'Brand', width: '35%' },
      { field: 'color', header: 'Color', width: '25%' }
    ];
  }

  resettable() {
    this.isLoading = true;
    this.cars1 = [...this.cars1];
    // this.dataTable.reset();
    setTimeout( () =>{
      this.isLoading =false;
    },3)
  }

}

Answer №2

If you need to adjust the width of your table columns dynamically, you can create a button or event and link it to a function that handles this task effectively. I have personally tested this method and found it to be very successful.

ngOnInit() {
     this.list =  myservice.getList();
     this.adjustColumnWidth();
}

adjustColumnWidth(){
   this.cols = [
        { field: 'a', header: 'A', width: '25%'},
        { field: 'b', header: 'B', width: '15%' },
        { field: 'c', header: 'C', width: '35%' },
        { field: 'd', header: 'D', width: '25%' }
    ];
}

In your html file:

<button pButton type="button" (click)="adjustColumnWidth()" label="Adjust Width"></button>

Answer №3

The p-table feature saves column widths in either localStorage or sessionStorage within an object with the parameter "columnWidths". If you wish to reset the columns width, the easiest way is to delete it.

sessionStorage.removeItem('object name'); or localStorage.removeItem('object name');

The object name is specified in the p-table tag using the attribute stateKey="object name"

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

Removing information from the app.component.html file in Angular 6 and reflecting those updates in the view

I currently have a service that retrieves a list of data and displays it within the app.component.html. Below is the code snippet used to display the data: <ul> <li *ngFor="let data of retrieveData"> {{ data.id }} - {{data.title} ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

Eslint for Typescript in Vue is throwing an error with a message "Unexpected token, expecting ','. Make sure to

Whenever I attempted to utilize vue's type assertion, I kept encountering this eslint error. To illustrate, consider the following snippet: data: function () { return { sellerIdToListings: {} as any, // 'as' Unexpected to ...

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

Dynamically validate AngularJS forms with JSON Schema

I am currently trying to dynamically validate JSON in AngularJS. Unfortunately, I have encountered an issue with loading fields from the schema onto the page. My understanding of AngularJS is limited as I am still new to it. Although I have managed to cr ...

Generating a text input field with multiple lines

<!DOCTYPE html> <html> <body> <p>Press the button to generate a File Upload Button.</p> <button onclick="myFunction()">Click here</button> <script> function myFunction() { var x = document.createElemen ...

Creating a .env file using Vanilla JavaScript to securely store and conceal tokens

I am currently working on a vanilla JavaScript project. Within the app.js file, I am making an API call to retrieve specific values. Initially, I tested the API using Postman by including all the necessary headers there and then implemented the code in my ...

Utilizing TypeScript to Define Object Properties with String Keys and Values within Parentheses

I am in the process of developing a telegram bot I have the need to save all my messages as constants My message schema is structured as follows: type MessagesSchema = { [K in keyof typeof MessagesEnum]: string } Here is an example implementatio ...

Learning to incorporate animation in Angular2 using Dart is a valuable skill to have in

Is there anyone who can assist me in grasping the concept of utilizing angular2 animations in dart? I have referred to the documentation mentioning an AnimationBuilder class, but I was unable to locate it. ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

employ the inverse Euler application

var a = new THREE.Euler( 0, 1, 1.57, 'YXZ' ); var b = new THREE.Vector3( 1, 0, 1 ); var c = b.applyEuler(a); In order to get the value of c using b.applyEuler(a), I am looking for the reverse operation involving applyEuler. Given that the value ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

Remove an item from an array of objects based on its value

Within the array of nested objects provided below: [ { "items": [ { "name": "See data", "href": "/data", }, { ...

"Adjust the placement of a personalized marker on a Google Map using google-map-react

I have incorporated google-map-react into my React project and I have designed custom markers. The markers are displayed at the correct location but from the top left corner: https://i.sstatic.net/e6lGN.png The red dot indicates the exact location. Howe ...

Transferring image data from Angular to ExpressJS using blobs

While attempting to send a blob image, I encountered an Error: Unexpected end of form when using multer with Serverless Framework. Upon checking console.log https://i.sstatic.net/s8VSs.png My understanding is that I need to append it to FormData before s ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...

Assigning the Style property to an element using a string that includes HTML tags

My HTML string is populated with elements such as button, li, span, and more. I am looking to add specific styles to buttons based on their class name. For example, if button.btn { some styles } and button.btn-success { some other styles } O ...

Exploring the effectiveness of React Hook Form using React Testing Library

My Component includes a form that, upon submission, utilizes Apollo's useLazyQuery to fetch data based on the form values. The form in the component is managed by React Hook Forms, with the handleSubmit controlled by RHF. <FormContainer onSubmit= ...

How to retrieve values from dynamically generated text boxes using ng-repeat in AngularJS

When using ng-repeat, I am able to display textboxes related to each item. Upon clicking the SaveAll button, I intend to retrieve all textbox values based on ITEM ID and save them to the database. <tr> <td> <table ng-repeat="item in ...

Ensure the header remains fixed when scrolling in an HTML page with Bootstrap

I created the following code. However, when I scroll down the table, the header disappears from view. I would like the header to always remain at the top, even when scrolling. Despite searching Google multiple times and trying various solutions, I have no ...