Exploring Angular 9: Experimenting with iterating over a collection of objects and performing validations

Forgive me if this is a basic question, but I am new to Angular 9 and json. I am attempting to iterate through a list and only create a table row if the correct ID matches the ID passed from the previous page link.

I am struggling to make the if statement work within the for loop, as it is not generating any output.

<table>
    <tr *ngFor="let tag of tags; if tag.id == tagged.id">
        <th>{{ tag.id }}</th>
        <th>{{ tag.manufacturer }}</th>
        <th>{{ tag.serial }}</th>
        <th>{{ tag.inspectedDate }}</th>
        <th>{{ tag.result }}</th>
        <th>{{ tag.actionNeeded }}</th>
        <th>{{ tag.inspectee }}</th>
        <th>{{ tag.certificateNumb }}</th>
        <th>{{ tag.nextInspection }}</th>
    </tr>
</table>

I have managed to get it working by using the following code, but I am aware that this is not the most efficient method and I am struggling to find or figure out the correct way to do it:

<table>
    <tr *ngFor="let tag of tags">
        <th *ngIf="tag.id == tagged.id">{{ tag.id }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.manufacturer }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.serial }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.inspectedDate }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.result }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.actionNeeded }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.inspectee }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.certificateNumb }}</th>
        <th *ngIf="tag.id == tagged.id">{{ tag.nextInspection }}</th>
    </tr>
</table>

Answer №1

If you want to iterate through a list using Angular, you can utilize ng-container as a placeholder element that won't generate any actual HTML tags. Then, implement the *ngIf structural directive within it, as shown below:

<ng-container *ngFor="let tag of tags">
  <tr *ngIf="tag.id == tagged.id">
     <th>...</th>
  </tr>
</ng-container>

If you find yourself needing to apply this type of filtering repeatedly, consider creating a custom pipe. Here's a basic example of how it could be implemented:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
    transform(arr: Array<any>, prop: string, value: any) {
       return arr.filter(x => x[prop] && x[prop] === value);
    }
}

You can then use this pipe in your template like so:

<tr *ngFor="let tag of tags | filter:'id':tagged.id">

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

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...

How can I code a script to import JSON data into MongoDB database?

I have a JSON file named "data.json" that contains an array of people's names as shown below: "data": [ { { "name":"John", "age":30, } { "name":"Mark", "age":45, } } ] I am ...

"Utilizing FormData in an IONIC 5 project with

While creating a user profile, I am encountering an issue where the FormData being generated for sending is empty despite all other fields having values. Below is the code snippet from cadastro.ts: import { Component, OnInit } from '@angular/core&ap ...

Updating the old version of an Angular app on Azure using VS Code can be challenging as the deployment process may not automatically replace

After making changes to my Angular App and testing it locally with 'ng serve', I used 'ng build' to generate artifacts in the 'dist' directory. Utilizing the Azure App Services extension in VS code, I selected the 'dist&a ...

Leveraging *ngIf in conjunction with routerLink

How can I apply "ngIf" to a routerLink instead of using a button? For example: *ngIf="auth.isAuthenticated()" (click)="auth.logout()" Using: <a [routerLink]="['/']">Logout ...

At what point does a vulnerability in a React or Angular library become a serious threat?

As a cybersecurity student, I have noticed numerous CVEs related to libraries used in React and Angular. One example is: │ Critical │ Prototype Pollution in minimist │ ├────────────── ...

Error TS2304: Unable to locate identifier 'RTCErrorEvent'

I am currently working on a WebRTC application using Quasar, typescript and Vue. In my code snippet below, I am encountering an issue where I don't get any errors in WebStorm (as it uses the project's eslint config), and I can navigate to the def ...

Retain the trailing zero value while employing the json.Unmarshal() method

This question is unique from the one found at Stop json.Marshal() from stripping trailing zero from floating point number because my concern is with unmarshaling (parsing the JSON-encoded data). In the snippet provided at https://play.golang.org/p/jrQ3OSv ...

When attempting to send JSON data to the server using a .ajax() post request, it seems to only be

I am encountering an issue where I am attempting to insert a JSON string into the database by making a call to a web service through an AJAX request. Strangely, when I debug the code using Chrome debugger, the string gets successfully inserted into the DB. ...

Value returned by Typescript

I have been attempting to retrieve a string from a typescript function - private _renderListAsync(): string { let _accHtml: string=''; // Local environment if (Environment.type === EnvironmentType.Local) { this._getMockLi ...

The Json request is invalid because it contains the @ symbol

After validating the Json data online, it appeared to be correct. However, when I attempted to call the json array key, the editor showed a Parsing error: Unexpected character '@' The editor in question is Visual Studio Code, and it seems as tho ...

Disable editing of all form controls within a template-based form

We are looking to implement a 'read-only' feature for certain users in our template-based form that utilizes Angular Material controls such as matInput and mat-select. My initial approach was to check user privileges and then iterate through the ...

Python encountering errors while attempting to load JSON file

I have a text file containing the following json: { "data sources" : [ "http://www.gcmap.com/" ] , "metros" : [ { "code" : "SCL" , "name" : "Santiago" , "country" : "CL" , "continent" : "South America" , "timezone" : -4 , "coordinates" : {"S" : 33, "W" : ...

Convert JSON to a MySQL query in PHP

I am attempting to run a query but for some reason the PHP code is not functioning properly. Despite my efforts, there have been no updates in my database. Could there possibly be errors somewhere? <? $json = file_get_contents('php://input&apo ...

Typescript error message TS2314: One type argument is required for the generic type 'Array<T>'

I recently started my journey in learning typescript and have written some basic code. class Learning { subjects: Array[string]; hoursPerDay: number; constructor(subj: Array[string], hrs: number) { this.subjects = subj; thi ...

Angular 2 is reporting the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource" when using the http.get function

Encountered the following issue: Response to preflight request fails access control check: 'Access-Control-Allow-Origin' header missing in requested resource. Issue arises when attempting a request to my web API from my Angular2 application: ...

Passing parameters to an Angular CLI ejected app

Currently, I am utilizing @angular/[email protected]. I have leveraged the new eject feature to modify the webpack configuration. Now, I find myself perplexed on how to pass parameters to my build process. For instance, how can I execute ng build --p ...

Change an array of JSON objects into a single string representation

Currently, I am working with jquery and have come across a JSON object array that needs to be converted into a specific string format. After some research, I found out about the "JSON.stringify" method but I am unsure of how to implement it in my scenario. ...

Leveraging parameters within a sequence of object properties

Within the realm of Angular, I am dealing with interfaces that take on a structure similar to this (please note that this code is not my own): export interface Vehicles { id: number; cars: Car; trucks: Truck; } Export interface Car { make: ...

Dropdown element with PrimeNG adorned with a span

I am trying to create a simple form with text inputs and dropdowns. I have successfully implemented the textInput, but I am struggling with the dropdowns. Below is the code that I have so far: <div class="p-grid p-dir-col p-offset-2"> ...