Guide to dynamically setting the index element with ngFor in Angular

When working with NgFor in Angular, I am interested in dynamically handling attributes using an index.

I have a collection of properties/interfaces that look like this:

vehicle1_Name,
vehicle2_Name,
vehicle3_Name
vehicle4_Name,
totalVehCount

To achieve this, I am utilizing a for-loop with totalVehCount.

numVehicle(n: number): Array<number> {
    return Array(n);
  }

<i class="fa fa-car" *ngFor="let veh of numVehicle(qt.totalVehCount);let indexOfelement=index;"></i>

The current implementation works smoothly, but I would like to dynamically display the title/tooltip as follows.

<i class="fa fa-car" title="{{qt.vehicle[indexOfelement+1]_Name}}" 
                                *ngFor="let veh of numVehicle(qt.totalVehCount);let indexOfelement=index;"></i>

How can I accomplish this?

For example, if totalVehCount = 1, it should be displayed like this:

 <i class="fa fa-car" title="{{qt.vehicle1_Name}}"></i>

If totalVehCount = 2, then it should be displayed like:

<i class="fa fa-car" title="{{qt.vehicle1_Name}}"></i>
<i class="fa fa-car" title="{{qt.vehicle2_Name}}"></i>

Answer №1

If the current structure of your data is spread across multiple properties, it can be challenging to iterate through efficiently. I recommend organizing the data into an array format like this:

cars = [{ brand: "Toyota"}, { brand: "BMW"}, { brand: "Honda"}, { brand: "Fiat"}]

To maintain the original properties while creating the array, you can use this method:

cars = [car1_Brand, car2_Brand, car3_Brand, car4_Brand].map(brand => { brand });

Subsequently, in your template, you can easily iterate over the array using:

<ng-container *ngIf="let car of cars">
  <i class="fa fa-car" [title]="car.brand"></i>
</ng-container> 

This solution may need adjustments based on the dynamic nature of your data. It's crucial to have a well-structured data format for easier manipulation.

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

How can esbuild be used to load .wglsl files in Typescript files?

I'm currently utilizing esbuild to bundle my Typescript code, but I'm facing a challenge with configuring a loader for ".wgsl" files. Here is my app.ts file: import shader from './shader.wgsl'; //webgpu logic This is my shader.d.ts fi ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Best Practices for Showing JSON Data from MongoDB in an Angular Material Table

Desire I'm trying to extract data from MongoDB and exhibit it in an Angular Material Table. Problem Even though I can view the results of my MongoDB query in the console/terminal, the Chrome browser console indicates that my JSON data has been save ...

React and TypeScript warns about possible undefined object

certificate?: any; <S.Contents>{certificate[0]}</S.Contents> <S.Contents>{certificate[1]}</S.Contents> <S.Contents>{certificate[3]}</S.Contents> If I set the type of props to `any` and use it as an index of an array, e ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Necessary CSS selector input equivalent in Reactive Forms

Is there a similar CSS method like input:required {CSS} to style all the reactive form fields in Angular that are set as required using Validators.required in their formControl? Or is there another approach to achieve this with CSS? ...

Conflicts arise when trying to create several objects with different material types in ThreeJS within the

Adding a star to the scene caused all objects in the scene to turn white and the perspective of the objects to glitch. Switching the materialStar to new THREE.MeshBasicMaterial fixed the rendering issue. It appears that the problem stems from having multip ...

Using Typescript to resolve a package from a location other than the default node_modules directory

I am currently delving into typescript and eager to start dabbling in creating packages. Here is the current layout of my project: myProject/ ├── node_modules/ ├── src/ │ ├── app │ ├── index.ts │ ├── packages ...

Tips for deploying an Angular Universal 9 application on a live server

Our Angular 9 app functions perfectly when deployed on an IIS server. We also have a version of the app that has been integrated with Universal by another company. Now, we need to figure out how to deploy our app with server-side rendering into productio ...

Can you point me in the right direction for declaring the ImageObject format in Angular?

To create an Image Slider similar to the one shown here, I need to load images from a source. However, I'm unsure about where exactly in the file (possibly in the component.ts?) I should declare them: imageObject: Array<object> = [{ ...

Access the Ionic2 App through the Slider option

Trying out Ionic 2 and facing an issue. Created a default side-menu app from CLI with a slider. Need to start the actual side-menu app from the last slide on button click or anchor link. My app.ts: @Component({ templateUrl: 'build/app.html' }) ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

The custom FontAwesome icon is failing to display properly

UPDATE : Here is the StackBlitz as requested. A custom SVG icon was created based on instructions provided by FontAwesome's collaborator found here. Despite mirroring the exact element structure of FontAwesome's icons, the custom icon does not ...

Working with type-agnostic values in a type-agnostic list within a type-agnostic class using Typescript

I'm currently attempting to add a generic object to a list of other generic objects within a generic class. There seems to be an issue with the semantics, but I can't pinpoint exactly what the problem is. type EventCallback<I, O> = (event ...

Interacting between two occurrences of the identical Angular component

Within a Razor view, I include an angular component: <my-widget id="myWidget" isfullscreen="false" class="some-class"></my-widget> Upon clicking the 'Popup' button, a popup appears in an iframe and the s ...

Generating form groups programmaticallyORDynamically

I recently utilized angular-archwizard to implement a wizard step with *ngFor However, I encountered an issue on how to create a dynamic formGroup for each step. In the code below, I managed to create a single formGroup for all steps, but my goal is to ha ...

Interface key error caused by the TypeScript template literal

Version 4.4.3 of Typescript Demo Playground Example -- interface IDocument { [added_: `added_${string}`]: number[] | undefined; } const id = 'id'; const document: IDocument = { [`added_${id}`]: [1970] } My Attempts: I made sure that id in ...

"Encountering a 404 (Not Found) error when attempting to access local backend APIs through Angular

Recently, I integrated Angular Universal into my project to enhance performance and improve SEO. Everything was working smoothly when I ran 'ng serve', with the app able to communicate with the backend. However, when I tried running 'npm run ...

Is there a way to ensure that Tailwind CSS loads before rendering components in NextJS?

While developing my web application, I encountered an issue with the tailwind CSS styling. The styles seem to load correctly, but there is a slight delay before they take effect. This results in users seeing the unstyled version of the website briefly befo ...

Error: The checkbox was clicked, but an undefined property (includes) cannot be read

Link to live project preview on CodeSandbox Visit the product page with checkbox I have developed a code snippet that allows users to filter products by checking a box labeled "Show Consignment Products Only", displaying only those products with the term ...