Dealing with undefined arrays in Angular across multiple templates: Best practices

I'm currently developing a search screen for an application and I've come up with three possible outcomes for the results section.

  • If the user hasn't searched yet, then show nothing.
  • If the user searches and the array is empty, display "no results".
  • If the user searches and the array isn't empty, loop through and display the results.

I've managed to make it work fine for empty vs non-empty arrays:

<ng-container *ngIf="results.length">
    <div class="result" *ngFor="let result of results">
        <a href="link-goes-here">Open Result</a>
        <search-result  [result]="result"></search-result>
    </div>
</ng-container>
<ng-container #elseBlock>
    No Results found.
</ng-container>

However, when I try to include a check for results being undefined, it doesn't seem to work as expected. I attempted to use [ngSwitch], but that also failed. Alternatively, I could create a boolean variable starting as false, then set to true after the first search, but I prefer having my array start as undefined and then get assigned after the initial search.

Answer №1

This code snippet addresses the three possible outcomes. Assuming that 'results' is null or undefined by default, the script first checks for its existence. If it exists, then it checks if it contains any values. If the user has not initiated a search yet, the *ngIf statement will return false and no content will be rendered.

<ng-container *ngIf="results">
    <ng-container *ngIf="results.length > 0; else elseBlock >
       <div class="result" *ngFor="let result of results">
          <a href="link-goes-here">Open Result</a>
          <search-result  [result]="result"></search-result>
       </div>
    </ng-container>

    <ng-template #elseBlock>
        No Results available.
    </ng-template>

</ng-container>

Answer №2

Make sure to utilize the safe navigation operator ?. when dealing with possible null or undefined results, otherwise the elseBlock will be displayed.

<ng-container *ngIf="results?.length;else elseBlock">
    <div class="result" *ngFor="let result of results">
        <a href="link-goes-here">Open Result</a>
        <search-result  [result]="result"></search-result>
    </div>
</ng-container>

<ng-template #elseBlock>
    No Results found.
</ng-template>

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

Bringing in information from a TypeScript document

I'm having trouble importing an object from one TypeScript file to another. Here is the code I am working with: import mongoose from "mongoose"; import Note from './models/notes'; import User from './models/users'; import ...

Creating a default option of "please select" on an Angular select element with a null value for validation

Within my Angular application, I am using a select element with an ngFor loop: <select formControlName="type" required> <option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option> </select> When view ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

Why is Vite's hot reloading feature displaying unpredictable outcomes?

I have a unique setup consisting of Vite, Typescript, and Vue 3 SPA utilizing "script setup". This app is equipped with Urql to query data from a GraphQL endpoint. An interesting occurrence happens where the query results are only displayed after the comp ...

When attempting to build a production version of an Angular Ionic Capacitor project, a TypeError occurred stating that it cannot read the property 'updateClassDeclaration'

A short while back, I didn't encounter this error, but after executing npx audit fix --force, I started getting this error when running npm run build in my Ionic capacitor project: Module build failed (from ./node_modules/@angular-devkit/build-angular ...

Launch a modal window that displays a form generated using ngx-formly, which is nested within another form also created with

I have been utilizing ngx-formly to generate Angular forms dynamically from JSON data, and it has been working smoothly. One interesting scenario I encountered involves a custom button on a form that needs to open a modal dialog containing another form upo ...

What is the best way to retrieve the chosen item within a Tabmenu component in Primeng?

I have created a simple array of MenuItem objects to populate the Tabmenu component from Primeng. Here is an example: .ts file: items = MenuItem[]; activeItem = MenuItem; //constructor, etc... ngOnInit() { this.items = [ {label: &a ...

Unable to perform Undo function in monaco editor

Currently in my Angular 7 project, I have integrated the Monaco editor for coding purposes. One issue I am facing is that when I make a change to the code and then press ctrl+z to undo it, the previous code is successfully restored. However, if I change th ...

Conflicting React types found in pnpm monorepo

In the process of converting an inherited monorepo from yarn+lerna to pnpm workspaces, I am encountering some issues. Specifically, there are mismatching React versions causing errors in typescript. It seems that TypeScript is not recognizing the closest @ ...

What is the process of creating a typeorm relationship between orders and products?

My Orders Entity file in TypeOrm looks like this: @Entity('orders') export class OrdersEntity { @PrimaryGeneratedColumn('uuid') id: string; @CreateDateColumn() created: Date; @UpdateDateColumn() updated: Date; @Column('t ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

Exploring the Various Path Options in Angular 2 Routing

As a newcomer to Angular and Node JS, I am currently working on an application and struggling with how to efficiently navigate between my different components. Users can input the name of a user and add books associated with them When clicking on a book ...

Suggestions for the output of an Angular 2 async validator when employing observables

How should the customerNameValidator handle the async validation result for the 'customerName' FormControl invalidation? this.customerForm = this.formBuilder.group({ customerName: [this.newCustomerName, [Validators.minLength(2), Validators.requ ...

Learn the process of importing data types from the Firebase Admin Node.js SDK

I am currently facing a challenge with importing the DecodedIDToken type from the https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.decodedidtoken. I need this type to be able to assign it to the value in the .then() callback when v ...

Tips for organizing your Typescript code in Visual Studio Code: avoid breaking parameters onto a

Currently, I am working on an Angular project using Visual Studio Code and encountering an irritating issue with the format document settings for Typescript files. It keeps breaking parameters to a new line: Here is an example of the code before formattin ...

Angular 7: module not found error - unable to locate 'underscore' package

Currently tackling a project using Angular 7. Attempted to add npm install --save @types/underscore but encountered the following errors: npm WARN @agm/[email protected] requires a peer of @angular/common@^5.0.0 || ^6.0.0 but none is installe ...

Angular4 does not recognize this.form.get as a valid function

While working on my Angular 4 application, I encountered an issue with data binding to a form. Despite the code for binding appearing correct, there seems to be a problem that I can't quite pinpoint. Upon debugging the application, I noticed that the ...

Retrieve all users using Auth0 with Angular 2

I am trying to retrieve all users from auth0 using angular2 by following the documentation provided at https://auth0.com/docs/api/management/v2#!/Users/get_users. Here is what I have attempted so far. I understand that I need to include the access token, ...

How can items be categorized by their color, size, and design?

[{ boxNoFrom: 1, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" { boxNoFrom: 13, boxs: [{…}], color: "ESPRESSO", size: "2X", style: "ZIP UP" }, { boxNoFrom: ...