The Observable's value remains hidden when it is at 0 (Zero)

I am working with Angular 8 and implementing the following code:

<ng-container *ngIf="(count$ | async) as count; else loader">{{count}}</ng-container>
<ng-template #loader>
    loading
</ng-template>

The variable count$ is of type Observable<number> ...

When the value of count$ is 1, 2, etc it displays correctly.

However, when the value of count$ is 0, it only shows loading.

Any thoughts on why this may be happening?

Answer №1

To efficiently test the value of an observable in a condition while also displaying it in the view, you can implement nested ng-container elements. The first container retrieves the value of count using a specific method outlined in this informative article. Subsequently, the second container utilizes this value within both the condition and the view. This design enables the reutilization of the value without necessitating multiple subscriptions to the same observable.

<ng-container *ngIf="{ count: count$ | async } as data">
  <ng-container *ngIf="data.count === 0 || data.count > 0; else loader">
    {{data.count}}
  </ng-container>
</ng-container>
<ng-template #loader>
  loading
</ng-template>

For a practical demonstration, refer to this stackblitz showcase.

Answer №2

When the value is falsy, like in this case: Boolean(0) === false. Nothing out of the ordinary ;)

UPDATE:

.ts

this.counter$;

constructor() {
  this.counter$ = interval(2000).pipe(map(i => `${i}`));
}

.html

<ng-container *ngIf="counter$ | async as counter; else loader">
  {{ counter }}
</ng-container>
<ng-template #loader>
  loading
</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

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

The items are not displayed in the app.component.html file

I am having trouble displaying the product list in an HTML file. Despite receiving the product data in a JavaScript message, it is not showing up when I try to list it in the HTML. Can anyone assist me in resolving this issue? Below is the code snippet: im ...

Customizing input element styling with Angular Reactive Forms validation rules

My current reactive form setup is as follows: this.loginForm = this._fb.group({ email: ['', [Validators.required, Validators.pattern('^[A-Za-z0-9._%+-]<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99b2d9fef4f ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...

In Angular, you can achieve two-way binding between a mat tab group and an array in your typescript file. But what's the best way to programmatically switch to a specific mat-tab using types

Check out the code snippet below. I have a mat tab group with a mat tab corresponding to each ValidationStep object in the validationSteps[] array in my TypeScript file through two-way binding. Whenever I add a new element to the array, a new tab is dynam ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

Injecting dynamic components into the root of an Angular2 application

Seeking Solution I am exploring the most effective method to insert a pre-defined component into the main structure of an application and apply @Input() options to that component. Necessity This is essential for developing features like modals/tooltips ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors? In this example (run), this.x is accessed in the method initY before it's initialized in the constructor: class A { readonly x: number rea ...

Tips for Structuring Code in a Resource Management Phaser Typescript Project

I'm currently developing a resource-management game and require a "collection manager" to streamline interactions between states and objects in Typescript. Let's imagine the game revolves around nurturing cats. In one state, players advance time ...

The challenges of type verification in Redux reducer

I'm currently facing two specific challenges with Typescript and the Redux reducer. Reducer: const defaultState = { selectedLocation: { id: 0, name: 'No Location' }, allLocations: [{ id: 0, name: 'No Location' }], sele ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

How can I display data both as a dropdown and an autocomplete in Angular using a textbox?

There is a textbox with autocomplete functionality. When the user clicks on the textbox, an API call is made with two parameters - Pubid and Date. The data is then displayed in a dropdown with autocomplete feature. Now I am attempting to have the data app ...

Incorporate the teachings of removing the nullable object key when its value is anything but 'true'

When working with Angular, I have encountered a scenario where my interface includes a nullable boolean property. However, as a developer and maintainer of the system, I know that this property only serves a purpose when it is set to 'true'. Henc ...

Guide on including a viewmodel object in cookies using AngularJS 2

Recently, I've been attempting to store viewmodel objects in cookies using AngularJS2. Despite my efforts, I haven't managed to make it work yet. private setCookie(name: string, value: any, expireDays: number, path: string = "") { let d: Dat ...

Execute a sequence of HTTP requests within an Angular interceptor or service when certain values are found to be null

My goal is to send a series of http requests in order to retrieve essential data that needs to be added to my request parameters for backend logging reasons. For instance, I require the userName, which can be obtained from the Microsoft endpoint: by fetc ...

What is the process for including or excluding a modifier from a sentence?

I've been experimenting with the TypeScript compiler API for transforming TypeScript code, but I'm struggling to find a concise method for adding or removing modifiers in a generic way. The solution I currently have is as follows: function remove ...

Encountering the error message "Attempting to access a null or undefined value while populating an array within a loop in TypeScript."

I am relatively new to TypeScript and currently working on one of my initial projects in Microsoft Makecode Arcade. I am attempting to populate an array as a class property using a loop. class Game { grid: number[][] constructor() { for (l ...

Angular issue: Element 'mdb-select' is unrecognized

While working with Angular's MDB pro version, I encountered a peculiar error message: mdb-select is now a known element I suspect that I may have missed an import somewhere, but the specific one eludes me This snippet shows my component.html file: ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...