Angular 5 is rendering a div even if there is no content present

I am currently using

Angular 5.2

Firestore

When using *ngIf isContent else noContent, my goal is to only render an Observable if it contains data. However, I am facing an issue where the logic always renders isContent even when there is no data present. Despite reviewing several similar questions on Stack Overflow, I cannot seem to identify what I am doing wrong. Can you please help me troubleshoot this?

Below is the code snippet causing the problem:

<ng-container *ngIf="months2025 | async as months; else nocontent">

  #### RENDERING REGARDLESS OF MONTHS2025 ####
  <div class="column">
    <h1>2025</h1> #### <-- THIS SHOWS UP ####
    <ul>
      <li *ngFor="let month of months">
        <a href={{month.url}}> {{ month.fileName }} </a>
      </li>
    </ul>
  </div>

</ng-container>

#### NOT RENDERING WHEN NOCONTENT ####
<ng-template #nocontent>
</ng-template>

Here is the corresponding component.ts:

export class MinutesComponent {
  monthsArray2025: AngularFirestoreCollection<any>;
  months2025: Observable<any[]>;

  constructor(private afs: AngularFirestore) {
    this.monthsArray2025 = afs.collection<any>('minutes', ref => ref.where('year', '==', 2025);
    this.months2025 = this.monthsArray2025.valueChanges();
  }
}

Answer №1

It seems that you are receiving an empty array from your observable, like this: [], which is considered to be truthy.

Make sure to also check the length of the array.

<ng-container *ngIf="(months2025  | async) as months && months.length>0; else nocontent">

As I mentioned earlier, there is an ongoing issue in Angular that aims to address the need for a construct allowing such checks, which can be found here.

One workaround is to use mapping to force undefined/null when dealing with an empty array.

this.months2025 = this.monthsArray2025.valueChanges().pipe(map(months => months && months.length>0 ? months : undefined));

Another option is to utilize two separate *ngIf statements, as suggested by @John in his response here

Answer №2

Currently, there is an ongoing discussion on this particular issue in a Github thread. To address it temporarily, I have come up with a solution involving the use of two *ngIf containers.

<ng-container *ngIf="months2025 | async as months">
  <ng-container *ngIf="months.length > 0; else nocontent">
    <div class="column">
      <li *ngFor="let month of months">
        <a href={{month.url}}> {{ month.fileName }} </a>
      </li>
    </div>
  </ng-container>
</ng-container>

<ng-template #nocontent>
</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

Navigate through each file or image within a directory using Angular

I am facing a challenge with my app where each product has a gallery containing a random number of images, each with a completely unique name. These images are located in /src/assets/images/products/:id/. Currently, I am struggling to loop through and add ...

Using a single Angular component to dynamically load data based on the query string

I am curious if it is feasible to load data based on a query string. For instance, when the user clicks on the following link http://localhost:4200/earning/customers?type=archived, the data will be loaded using the same component CustomersComponent. Simila ...

Is there a way to customize the default MuiCheckbox icon in theme.ts?

How can I customize the icon default prop for Mui checkbox? I followed the instructions provided here and used a snippet from the documentation: const BpIcon = styled('span')(({ theme }) => ({ borderRadius: 3, width: 16, height: 16, .. ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Explore lengthy content within Angular 2 programming

I have a lengthy document consisting of 40000 words that I want to showcase in a visually appealing way, similar to HTML. I aim to include headers, paragraphs, and bold formatting for better readability. Currently, I am developing an Angular application. D ...

Bidirectional data binding in Angular 2 allows for communication between parent components and directives

Update: Experimenting with Angular2 Beta, I am working on incorporating an "editor" component template that includes a directive wrapping the Ace editor. In this scenario, the "editor" component acts as the parent of the Ace wrapper directive, and my goal ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Attempting to imitate a form using Angular 2's HTTP post functionality

I am working on an ionic2 application that requires authentication to be done on an existing PHP website and then execute certain requests within it. I do not have access to the source code of the website. Since I am using ionic2, CORS should not be an iss ...

React type-script does not trigger the onClick event for CheckBox

I have created a custom component called MyCheckBox (which I am using as a helper component). I imported this component into another one, but for some reason, the event is not being triggered when I try to click on it. Here is the code for reference: MyC ...

The information retrieved from the API is not appearing as expected within the Angular 9 ABP framework

I am facing an issue with populating data in my select control, which is located in the header child component. The data comes from an API, but for some reason, it is not displaying correctly. https://i.stack.imgur.com/6JMzn.png. ngOnInit() { thi ...

Passing Imported Module to Feature Module in Angular 7

In my Angular 7 app, I have set up a hierarchy of feature modules. The structure looks like this: app admin (UI module imported here) feature1 feature2 public Within the admin module, I have included a UI framework module. My question is, if modules ...

Encountered an error with API request while utilizing Cashfree in a React Native environment

I'm currently integrating cashfree into my react native app for processing payments. Here is a snippet of the code I'm using: import { CFPaymentGatewayService, CFErrorResponse, } from 'react-native-cashfree-pg-sdk'; import { CFDr ...

Every field displaying a description above the input

Is there a way to customize the default wrapper for all fields? I am looking to have the description displayed above the fields instead of below them, which is the default behavior for Bootstrap. Check out this StackBlitz example: https://stackblitz.com/ ...

Excluding properties based on type in Typescript using the Omit or Exclude utility types

I am looking to create a new type that selectively inherits properties from a parent type based on the data types of those properties. For instance, I aim to define a Post type that comprises only string values. type Post = { id: string; title: string ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

Retrieving variables from JavaScript files in TypeScript

Greetings, I am in the process of upgrading an existing Angular application from version 2 to 9. My approach involves first moving it to angular 4 and then continuing with the upgrades. I have successfully updated the necessary packages, but now I'm e ...

Typescript: Maximizing efficiency and accuracy

When it comes to developing Angular2 apps using Typescript, what are the essential best practices that we should adhere to? ...

Tips on using the `IsEqual` function to develop a tool that verifies the similarity of different data types

When working with TypeScript, I often utilize the type-fest npm package in my coding. For documentation purposes, I sometimes like to assert that two types are either equal or unequal. Here is an example: const b: IsEqual<{a: 1}, {a: 1}> = true; con ...

Integrating custom non-NPM JavaScript files into Angular 2

Currently, the application I am working on is running in an environment with angular 2.0.0 final using typescript and also utilizes angular-cli 1.0.0-beta.15. Since the development of the application involves multiple developers who all use typescript, I ...