Printing in HTML with Angular based on certain conditions

As I cycle through a list of products, I am verifying if the product Id is already included in an array of products (objects). If it is, then I print the quantity. If not, I attempt to print 0. Here is the code snippet I have been working on:

<ion-item class="added" *ngFor="let item of fetchProducts(); let key=index;">
  <ng-container *ngFor="let cartitem of cart">
     <span class="count" *ngIf="cartitem.p_id == item.p_id;">
         {{ cartitem.qty }}
     </span>
     <span class="count" *ngIf="cartitem.p_id !== item.p_id">
         0
     </span>
   </ng-container>
</ion-item>

I am looking for a way to display 0 if item is not found within the cartitem.

Answer №1

One way to achieve this is by using the ternary operator as shown in the example below:

<ng-container  *ngFor="let product of products" >
     <span class="quantity">
      {{product.id === item.id ? product.quantity : 0 }}
     </span>
</ng-container>

Answer №2

Utilize the *ngIf else condition within a for loop like this -

<ion-item class="added" *ngFor="let item of fetchProducts();let key=index;">
  <ng-container *ngFor="let cartitem of cart">
    <span class="count" *ngIf="cartitem.p_id==item.p_id; then content else other_content">
    </span>
    <ng-template #content>{{cartitem.qty}}</ng-template>
    <ng-template #other_content>0</ng-template>

  </ng-container>
</ion-item>

Answer №3

To enhance code readability, consider transferring template logic to the class itself.

The variables cart and products are already accessible within the class. Therefore, modify the fetchProducts function in the class to return the products list with quantity information included. Then, utilize a single ngFor loop in the template.

An alternative approach is to introduce a new function called getProductsWithQuantity...

Here's an example implementation in your class:

public getProductsWithQuantity() {
    return this.fetchProducts().map(product => {
        ...product,
        quantity: this.getQuantity(product);
    });
}

private getQuantity(product) {
    const foundCartItem = this.cart.find(cartItem => product.id === cartItem.id);
    if (foundCartItem) {
        return foundCartItem.qty;
    }
    return 0;
}

Incorporate the following snippet into your template:

<ion-item class="added" *ngFor="let item of getProductsWithQuantity(); let key=index;">
   <span class="count">
       {{item.qty}}
   </span>
...

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 is the reason behind receiving undefined when using tableRow.get() in p5.js?

Currently, I am experimenting with incorporating geolocation data into a data table using p5. However, I have encountered an issue where p5 is unable to load data from tableRow.get(). When I print the values of lat and lon, it shows them as undefined. What ...

`HTTP Streaming with Axios in a Node JS Environment`

I am currently facing an issue while attempting to stream price data via HTTP (I'm surprised they aren't using websockets..). I usually use axios for making REST API requests, however, I am struggling to handle 'Transfer Encoding': &apo ...

Encountering an error while trying to generate volume in a custom Docker image on Google Cloud

I am working on an Angular application with Cypress and attempting to set up a pipeline configuration on Google Cloud Build. images: - 'gcr.io/$PROJECT_ID/e2e-tests' steps: # Install node_modules - name: node:10.16.3 entrypoint: npm ...

Locate the item within the array to retrieve the object's information

I have daily entries in the mongo database and I am attempting to locate a particular entry within an array. For instance, my goal is to find the Coca-Cola entry for this user on the current date using mongoose. "_id": ObjectId("ID"), "user_id": ObjectId( ...

Setting the OrbitControls Position in ThreeJS

Currently, I am saving the position of the OrbitControls by using .getAzimuthalAngle() and .getPolarAngle(). In the future, I would like to update these angles with slightly different values. I chose to utilize getAzimuthalAngle and getPolarAngle because ...

What steps are involved in creating a circular shape on canvas?

I am trying to create a circular shape in the canvas using the code below. The code involves moving an object with keyboard keys, and I need help making the canvas shape into a circle without affecting the functionality of the code. I attempted to modify t ...

What is the best method for transforming HTML into valid XHTML?

I'm dealing with a string of HTML, and in this particular example it appears as follows: <img src="somepic.jpg" someAtrib="1" > I'm currently attempting to create a regular expression that will match the 'img' node and add a sla ...

Each entry is linked and separated by a comma in the text

In the table I created, one of the columns displays values like A,B,C or D,E or F. Each entry in this column has a hyperlink below it that redirects the user to another page with the corresponding value passed as a parameter. However, currently, the hyperl ...

Having trouble setting up Raygun in Angular version 6 with TypeScript?

Encountering Setup Issue with Raygun in Angular Version 6 Using TypeScript Problem: ERROR in src/app/app.raygun.setup.ts(6,20): error TS2304: Cannot find name 'RaygunV2'. This specific line seems to be causing trouble: declare let rg4js: ...

What is the process for obtaining a push key in Firebase?

When a user submits data to the Firebase database, I need to handle the Key generated by that action in my own function. The challenge arises when a user fills out a form and sends data to our real-time DB. This data may include optional images, and I wan ...

Excess whitespace found in string within mat-option

Every time I retrieve text from the mat-option, I notice an additional space at the end of the string. This causes my assertion to fail when trying to compare it with the expected value. This issue is new to me, and I'm unsure how to address it. Why ...

Ensure that at least one checkbox is selected by using custom validation in jQuery

My form has checkboxes for gender (male and female) and a set of checkboxes for days of the week (Monday to Sunday). I need to set validation rules so that at least one gender and one day is selected. Below is my jQuery code: $(document).ready(function( ...

Combining objects into an array of objects with matching keys

Seeking to combine objects with the same key within an array of objects. The initial object structure is as follows: const cultures = { "en-us": { "path": "/en/playground/copy/", "startItem": { ...

Calculate the combined sum and alter the values of three input fields

There are three text boxes (testbox, testbox2, testbox3) that receive values from an input field, radio button selection, and checkbox. The correct values are displayed in testbox, testbox2, testbox3. Additionally, the sum of testbox, testbox2, testbox3 n ...

What is the best way to remove an exported JavaScript file from Node.js?

In my Node.js library package called "OasisLib," there is a file named TypeGenerator.ts. The specific logic within the file is not crucial, but it requires access to files in the filesystem during the project build process. To achieve this, we utilized let ...

What is preventing me from connecting to dockerized npm from my host machine?

Issue - A server running inside a docker container is not responding when accessed from outside the container on an OSX host. web: image: my_web build: context: ./ dockerfile: web.docker container_name: my_web networks: ...

Comparing the value of a div using jQuery: A comprehensive guide

Can anyone please assist me with this? I am trying to compare the values of a div from a PHP array using jQuery. This is my PHP array: $newarray=array('cat','cap','catm','cam','catp','camp'); I ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Value binding with conditional rendering in VueJS 2

My goal is to utilize VueJS 2 to render an inline condition while simultaneously adding a value to a DOM element. I am aware that I can use v-if to control the visibility of elements based on conditions, but how can I achieve an inline condition? For exam ...

The texture loaded by TextureLoader.load() has no defined image in IE11

I recently used Three.js to create a stunning 3D globe for my website. To display textures on this globe, I implemented the following code snippet: var loader = new THREE.TextureLoader(); loader.load(imageString, function (texture) { var sphere = ne ...