Home > other >  How to hide a table and a button when there's no data to show
How to hide a table and a button when there's no data to show

Time:10-31

I'm trying to hide the table, and the 'changeState' button when there's no data in it. The best I've got is for the 'No entries in the list!' message is to pop up for a few seconds, and then disappears, with the table and the button back on the screen. Can anyone help me with this one?

Here's my HTML:

<app-header [isHidden]="isHiddenProgressBar"></app-header>
<div class="change">
  <button (click)="changeState()" *ngIf="showButton" color="primary" mat-raised-button>Change state</button>
</div>
<div class="list">
  <app-list *ngIf="visible" [changeObjects]="data"></app-list>
  <ng-container *ngIf="!data">
    No entries in the list!
    </ng-container>
</div>

And here's a .ts part:

this.data = this.objects;
this.visible = this.objects != null && this.objects.length > 0;
this.showButton = true;

//if statement added when there's no data in the list
if(!this.objects) {
    this.showButton = false;
    this.visible = false;
}

Thank you, guys!

CodePudding user response:

The lines

this.visible = !this.objects && this.objects.length > 0;

And

if (!this.objects) {

It will not check for an undefined or empty array.

If objects is an empty array like this:

this.objects = [];

Or is undefined:

this.objects = undefined;

Then the conditions to cover these cases should be:

this.visible = (this.objects !== undefined) && (this.objects.length > 0);

And

if (this.objects === undefined || this.objects?.length === 0) {

If you initialize the objects with an array of sample data like this:

objects: any[] = [
  { id: 1, desc: 'one' },
  { id: 2, desc: 'two' },
  { id: 3, desc: 'three' },
];

Then the above suggested conditions will give you the visible button and list for non-empty list, and for empty and undefined data will give you the hidden button and list.

I would recommend embedding console.log() statements to help debug these types of conditions in the future.

  • Related