What is the best way to generate a distinct identifier for every div element on a

Currently, I am working with Angular 2 and have a div element that I need to repeat in my HTML markup. This particular div contains a click event attached to it. Here is the code snippet:

HTML:

<div class="row">
    <button class="btn btn-primary" (click)="addExtra">
        Add Extra</button>
    </div>

    <div *ngFor="let val of addExtra">
        <div class="row">
            <div class="col-md-2">
                <label for="title">Title</label>
            </div>
            <div class="col-md-8">
                <input type="text" id="title" style="width:100%" class="form-control" />
            </div>
        </div>
    </div>
</div>

The TypeScript function associated with the button is as follows:

class MyClass {
    // Other lines of code...

    addExtra(): void {
        this.addExtra.push("inserted");
    }
}

Do you have any suggestions on how to assign a unique identifier to each dynamically added div? My goal is to include a delete button for each individual div.

Answer №1

To access the index, you can utilize the index variable:

<div *ngFor="let val of addExtra let i=index" [id]="'id'+i">

When dealing with a delete button, the id property is not necessary. You can opt for:

<div *ngFor="let val of addExtra">
  <button (click)="delete(val)">delete</button>

Alternatively, you can use:

<div *ngFor="let val of addExtra let i=index">
  <button (click)="delete(i)">delete</button>

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

Utilize the CSS class or variable within an Angular TypeScript file for enhanced styling and functionality

Is it possible to utilize the scss class or variable in a typescript file? scss .thisIsGreen { color: green; } .thisIsBlue { color: blue; } Alternatively, you can use $thisIsGreen { color: green; } $thisIsBlue { color: blue; } Now, I want to ...

Having trouble declaring a module in an npm package with Typescript?

I'm currently working on a project using Vue.js and TypeScript. Within project "A," I am utilizing a private npm package called "B," which serves as a component library. This package "B" also incorporates another library, 'tiptap,' which unf ...

Verify if the reactive form retains its original values

In my Angular 6 project, I have a reactive form with numerous fields including dropdowns and number inputs. Some of these fields start with empty values while others default to true. Users are allowed to select any combination of fields, making it impossi ...

Is there an alternative course of action since determining if Observable is empty is not feasible?

I am diving into Angular 11 and exploring the world of Observables and Subjects as a beginner. Within my application, I have a mat-autocomplete component that organizes its results into categories. One of these categories is dedicated to articles, and I&a ...

Display the HTML tag inside a cell of a mat-table

I am currently exploring options to display an HTML tag within a cell of a mat-table in Angular. My goal is to show a colored circle next to the cell value. I have searched online for solutions, but haven't found one that works. If anyone has any insi ...

ElevationScroll expects the 'children' prop to be a single child component of type 'ReactElement<any, string>'

I am currently working on integrating the Elevate AppBar from Material UI into my application using the following code: interface Props { children: React.ReactElement; } export const ElevationScroll = ({children}: Props) => { const trigger = u ...

Divide a string using multiple delimiters just one time

Having trouble splitting a string with various delimiters just once? It can be tricky! For instance: test/date-2020-02-10Xinfo My goal is to create an array like this: [test,Date,2020-02-10,info] I've experimented with different approaches, such ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

What are the advantages of using interfaces in React?

Exploring Typescript's interface and its application in React has been an interesting journey for me. It seems that interfaces are used to define specific props that can be passed, acting as a form of protection against passing irrelevant props. My qu ...

Is it possible to use TypeScript or Angular to disable or remove arrow key navigation from a PrimeNG Table programmatically?

Is there a way to programmatically prevent left and right arrow key navigation in a PrimeNG Table with cell editing, without the need to modify the Table component source code? You can check out an example here: Angular Primeng Tableedit Demo code. I mana ...

Encountering issues in Angular 2 when attempting to pass data into root component through ng-content and binding. Objective: Creating a reusable form component

I currently have a .NET MVC application and I'm looking to integrate Angular 2 into it. The structure of my page is as follows: <html> <head>css imports and jquery imports</head> <body> <div> a bunch of table ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Printing reports in Angular 9

I have a requirement in my Angular 9 application to generate and print reports. 1. I am looking for suggestions on how to handle printing reports where a user triggers the action by clicking a button, and the report data needs to be fetched from the datab ...

The Firebase Cloud Function is failing to trigger on the onCreate event within the Firebase Realtime Database

I recently deployed a function to Firebase with the following code: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; console.log('FILE LOADED'); const serviceAccount = require(' ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

You cannot set parameters using Angular's httpHeaders post method

Seeking assistance in obtaining the authtoken from RestAPI using a specific method. While the same URL, Parameters, and Headers provide the correct response in Postman, I am encountering a 401 unauthorized error in Angular. Can someone help me identify whe ...

Typescript absolute imports are not being recognized by Visual Studio Code

Encountered a similar unresolved query in another question thread: Absolute module path resolution in TypeScript files in Visual Studio Code. Facing the same issue with "typescript": "^4.5.5". Here is the content of my tsconfig.json: { ...

Resolve the issue of text overlapping on an image when zooming in

There seems to be an issue with overlapping text and images when zooming the page. I have included a screenshot for reference, please take a look and provide a solution. Thank you in advance.https://i.sstatic.net/oVlGN.png Here is the CSS code causing the ...

`How can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in: HTML: <div *ngFor="let report of reports"> <div *ngFor="let i of income"> <di ...