Angular - how to create a table resizable column and remember the width and size

1.1k Views Asked by At

I am developing an Angular application where we can add or remove columns according to user choice and priority.

I want to create a table with a resizable columns width and store the resized column in the local storage so that the user can see the same width when he/she visit again.

Currently I am using below directive to resize columns.

Create Resizable Table Columns with Angular Directives

I am stuck how to store column with in storage and use same width when user revisit.

1

There are 1 best solutions below

0
Nick Felker On

The best way to do this would be to explicitly store the values in localStorage or in some cloud database, depending on how broadly you want to remember.

You may need some method of identifying each column in your storage. This could be done with an additional Input.

You can retrieve these values in the ngOnInit function:

@Component({
  selector: 'th[resizable]',
  templateUrl: './resizable.component.html',
})
export class ResizableComponent implements OnInit {
  constructor() {}
  @HostBinding('style.width.px')
  width: number | null = null;
  @Input('key') key: string | null = null;

  ngOnInit() {
    if (this.key) {
      const value = localStorage.getItem(this.key)
      if (value) {
        this.width = parseInt(value) // Values stored as strings
      }
    }
  }

  onResize(width: any) {
    this.width = width;
    if (this.key) {
      localStorage.setItem(this.key, width.toString())
    }
  }
}