Ways to conceal a div when the array length is zero

I am faced with an issue regarding filtering a table of objects (Bills => Bill => Products => Product) using pipes. The pipe filtering works correctly, but even after the arrays have been filtered, the names (bill.name) are still visible when they do not display any results from the filtering. How can I troubleshoot this problem?

<span class="search-span">
    <input [(ngModel)]="searchText" placeholder="Start typing a product name..." class="search-input">
</span>
</div>
<hr>
<ng-container *ngFor="let bill of bills; let i = index">
    <div class="col-xs-12" *ngIf="bill.products?.length > 0">
        <h5>
            {{bill.name}} {{i === 0 ? '(this bill group)' : ''}}
        </h5>
    </div>          
    <div class="col-xs-3" *ngFor="let product of bill.products | filter : searchText">
        <div [class.selected]="isProductSelected(product)" (click)="selectProduct(product)">
            <span class="text">{{product.name}}</span>
        </div>
    </div>
</ng-container>

Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {

  transform(items: any, searchText: string): any {
    if (!items) return [];

    if (!searchText) return items;

    searchText = searchText.toLowerCase();

    return items.filter(it => {
      return it.name.toLowerCase().includes(searchText);
    });
  }
}

Answer №1

To optimize the code, consider moving the declaration of the filtered products to a <ng-container>

<ng-container *ngFor="let bill of bills; let i = index">
    <ng-container *ngIf="(bill.products | filter : searchText) as filtered">
       <ng-container *ngIf="filtered.length else noProducts">
          <div class="col-xs-12">
              <h5>
                  {{bill.name}} {{i === 0 ? '(this bill group)' : ''}}
              </h5>
          </div>          
          <div class="col-xs-3" *ngFor="let product of filtered">
              <div [class.selected]="isProductSelected(product)" (click)="selectProduct(product)">
                  <span class="text">{{product.name}}</span>
              </div>
          </div>
       </ng-container>
    </ng-container>
</ng-container>
<ng-template #noProducts>
   <span>No Products Found</span>
</ng-template>

Utilize nested <ng-container> elements for better organization and make use of *ngIf="XXX as YYY" syntax to improve code readability.

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

Launch an Angular 2 application in a separate tab, passing post parameters and retrieve the parameters within the Angular 2 framework

One of the requirements for my Angular 2 application is that it must be able to capture post parameters when opened in a new tab from a website. How can I achieve this functionality in Angular 2? Is there a way to capture post parameters using Angular 2? ...

The default selection is not showing up on an Angular 8 reactive form

I'm having some trouble with my Angular 8 reactive form that uses Bootstrap 4. Even though I've set the 'selected' attribute for the default option in the select element, it still doesn't display. Each time I have to manually selec ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

What is the best way to minimize the gap between each mat-grid-tile within a mat-grid-list?

<mat-grid-list cols="4" rowHeight="2:1"> <mat-grid-tile> <mat-form-field appearance="outline"> <mat-label>ID FEN</mat-label> <input matInput ...

What is the best way to prevent resizing of an Angular 2 Material md-textarea component?

Having trouble disabling the resizing option on an md-textarea. Here is the method I've attempted: <md-textarea md-no-resize rows="3"></md-textarea> Any suggestions on how to make it work? ...

Angular application experiencing issues with Bootstrap modal functionality

I'm attempting to utilize a Bootstrap modal within an Angular application by using classes in HTML, but it doesn't seem to be working - the modal is not displaying <div class="modal text-center" *ngIf="showmodal" tabindex=& ...

Connecting to a Postgres database with Typescript using Docker

Incorporating typeorm into my node project has presented some challenges. Initially, I set up the database using a docker container. However, upon stopping and restarting the container, the IP address kept changing. This led me to consider using the contai ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Can you guide me on utilizing the drag and drop functionality in Angular 8 CDK to merge two cards together?

My current challenge involves attempting to drag one card over another card in order to effectively "merge" or "combine" them, similar to the action of dragging an image onto a folder on a desktop. Despite utilizing HTML5 native drag and drop functionalit ...

What is the reason behind the restriction on creating circular dependencies in Ionic applications?

Working with Ionic, I have created 2 services to provide data: export class DocumentService { constructor(favorisService: FavorisService) { } async GetById(id: number): Promise<DocumentModel>{ let path = this.favorisService.getPath(); ...

Loading SVG templates dynamically in Angular can be done by utilizing a string

Is it possible to convert SVG content loaded from a server into a component template in Angular, with the ability to bind properties to it? For example, <tspan [attr.color]="textColor" ...>{{myText}}</tspan>. I have tried loading and ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

Websites experiencing horizontal scrolling functionalities

I have noticed that in my angular project, the website becomes horizontally scrollable when I log in. This only happens after logging in, and does not occur beforehand. I'm using angular calendars and Bootstrap for styling. What could be causing this ...

Transform a JSON object into a customized array format with the help of Angular 5 or plain JavaScript

I have a JSON dataset that appears as shown below. [{ {name: "box: 122",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58.116Z", "2018-01- 12T00:10:00.379Z"], y=[0, 3, 5]}, {name: "box: 125",x=["2018-01-12T00:01:56.480Z", "2018-01-12T00:05:58. ...

"Learn the process of connecting a value to a dropdown menu in Angular2 when triggered by a

I am currently working on a project where I have a dropdown that dynamically populates data from a database. <select (ngModelChange)="load($event)"> <option *ngFor="let type of types" [ngValue]="type">{{type.Name}}</option> </select& ...

Implementing unique behaviors based on data types in Typescript

I'm currently working on a React project where I need to showcase different types of articles, which I refer to as "Previews." These articles can be either text-based or contain images/videos. To handle this, I've defined two interfaces (TextPre ...

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

No Angular applications are currently functioning in any web browsers

https://i.stack.imgur.com/uZph5.pngOne of my Angular applications is having trouble running in the browser when I use the ng serve command. Each time I try, I receive the following message in the browser: This site can’t be reached. localhost took too ...

Conceal the initial value in a dropdown menu in a React component

I've set up a codesandbox to demonstrate the issue (https://codesandbox.io/s/practical-flower-k6cyl?file=/src/App.tsx) Is there a way to prevent the "AGE" text (first option) in the select box from being selected again? It should only be visible when ...

Transitioning Ionic2 RC0 - relocating custom libraries to the build directory after the removal of gulp

https://i.sstatic.net/0KLac.png The Gulp tool has been removed by the Ionic Team from their project. What is the alternative method to set up libraries? ...