How can I save the output of a function in a variable within an *ngIf directive and then utilize it within the same *ngIf block?

My scenario is as follows:

  1. I have a function that returns an array
  2. I need to conditionally render a component - only if the array exists and its length is greater than zero.
  3. The returned array should be passed as an @Input() to this component.

Since the content of the array is computed, I want to avoid calling the function multiple times and using a getter is not suitable for this situation.

I've experimented with various approaches, including:

<order-list *ngIf="customer.getOrders() as orders && orders.length > 0" [orders]="orders" ></order-list>
<order-list *ngIf="(customer.getOrders() as orders) && orders.length > 0" [orders]="orders" ></order-list>
<order-list *ngIf="(customer.getOrders()) as orders && (orders.length > 0)" [orders]="orders" ></order-list>

Unfortunately, I keep encountering several errors:

Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ("<div>

Parser Error: Unexpected token &&, expected identifier, keyword, or string at column

Parser Error: Missing expected ) at column 23

[ERROR ->]*ngIf="(customer.getOrders() as orders) && orders.length > 0"

Check out this stackblitz link for the issue above.

Answer №1

I have devised a new approach.

Instead of utilizing logical conjunction within a single *ngIf directive, I opted to enclose my component with <ng-container> and placed the first condition in its own *ngIf, followed by another *ngIf directive within the component itself. This setup still represents an AND logic for both conditions and functions seamlessly, as stated in the Angular documentation:

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout since it isn't rendered in the DOM.

<ng-container *ngIf="customer.getOrders() as orders">
    <order-list *ngIf="orders.length > 0" [orders]="orders" ></order-list>
</ng-container>

Check out the solution on Stackblitz.

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

Include the document when the query results in zero documents

Struggling to figure out how to add a document to a collection if a query returns no results. The current query lacks operators for checking the length or size of the result. How can this be achieved? The query in question: this.monthCollection = this.af ...

There seems to be an issue with receiving the message sent through postMessage()

I seem to be encountering an issue with my syntax while attempting to pass a variable to an iframe (for colorbox integration). Currently, I've allowed all domains on both ends for testing purposes. Here is the JavaScript code for the sender page: $(d ...

React-Three/Fiber Vertical Sticky Carousel for Mobile Devices using Three.js

https://i.sstatic.net/Z5F8K0mS.gif After stacking the sticky areas, I faced a challenge in adding text in the same style. Additionally, I created refs for each phone scene but the stickiness was lost. I am uncertain about what caused it to stick initially ...

Identifying Oversized Files on Safari Mobile: A Guide to Detecting Ignored Large Files in

Mobile browsers such as Safari have a tendency to ignore large files when passed in through the <input type="file">. For example, testing with a 10mb image file results in no trigger of any events - no change, no error, nothing. The user action is si ...

The deno bundle operation failed due to the absence of the 'getIterator' property on the type 'ReadableStream<R>'

When attempting to run deno with bundle, an error is encountered: error: TS2339 [ERROR]: Property 'getIterator' does not exist on type 'ReadableStream<R>'. return res.readable.getIterator(); ~~~~~~~~~~~ ...

Ways to Achieve the Following with JavaScript, Cascading Style Sheets, and Hypertext

Can someone help me convert this image into HTML/CSS code? I'm completely lost on how to do this and don't even know where to start searching for answers. Any assistance would be greatly appreciated. Thank you in advance. ...

The function in Angular 2 is invoked a total of four times

Take a look at this example. This example is derived from an Angular quick start sample, where the template invokes a function. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hell ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

Button for liking posts on Facebook made of titanium

I am attempting to publish a like for a page from my Titanium Alloy application. var fb = require('facebook'); fb.appid = "1234567890"; fb.permissions = ['public_profile', 'email', 'publish_actions']; fb.addEventLi ...

Combining numerous arrays of objects by a specific key

I'm struggling to merge multiple arrays of objects by a key. I've searched online for resources, but I only found information on merging two arrays of objects. My challenge is that I have an array containing multiple arrays of objects. response ...

limit mongoose search results to a specific year

Would it be possible to add an option for the api user to filter the wine query by year? However, if no year is specified, mongoose should not return an empty array. The same applies to the price property. For example, http://localhost:1234/api/wine?year= ...

Create a specific website link for searching on YouTube

Is there a way to generate a YouTube URL using JavaScript or PHP that searches for videos on a specific user account and displays the best title match at the top of the search results? This is the code I am currently using: <!DOCTYPE html> <head ...

An illustration of React's "component did mount" in JavaScript is shown in this example

As I embark on my journey with React, I find myself exploring code examples and stumbling upon an interesting discovery. You can find the link to the React tutorial here. Below is a snippet of code from the lifecycles section; componentDidMount() { this.t ...

A Simple Guide to Setting a Background Image in React Native with the Nativebase.io Library

What is the process for including a background image in React Native with the help of the Nativebase.io Library? I have a specific screen where I need to incorporate a background image, with all other elements positioned at the center of the image. ...

Unable to execute PHP alongside a JavaScript event listener

Using PHP, I am creating a canvas for writing and the text output will appear in a textarea (handled by other functions). There are additional input tags like a title to gather user input. The values from these input tags (title and textarea) will be submi ...

Utilizing a captured group from a regular expression as a key in replacing a string

Looking for help understanding the behavior displayed in this NodeJS 12 console code snippet. I'm attempting to replace a portion of a string with the result from a capture group. While it does work, using that capture group result as a key in an obje ...

Why isn't the styleClass property functioning properly within a PrimeNG Dialog?

I am having trouble applying the styleClass in primeNg correctly. Html file <p-dialog [(header)]="dialogText" [(visible)]="displayDlg" [modal]="true" [responsive]="true" styleClass='pDialog' > CSS File .pDialog{ width:700px; overflow ...

What is the best way to automatically show the latest localStorage data when a page is reloaded

There are two main goals I want to achieve with this section: I aim to show the updated high score each time the page is refreshed. Currently, the high score resets to 0 whenever the page is reloaded because of localStorage.setItem('high_score', ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

Maximizing Intellisense for custom Javascript services in VS Code using Typescript definitions

While developing a backend server with SailsJS, I encountered an issue where my model helper services and own services were not showing Intellisense. To address this, I set up typings, installed type definitions for lodash and node globally, and created js ...