What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below:

app.component.ts

export class AppComponent  {
  items = ['aaa', 'bbbbbb', 'ccccccccc']
}

app.component.html

<div class='form'>
  <ng-container *ngFor="let item of items">
    <label>{{item|uppercase}}:</label>
    <input [value]="item"/>
  </ng-container>
</div>

(View live example on StackBlitz: https://stackblitz.com/edit/angular-ptwq6t)

Is there an efficient way to link these "dynamic" labels with their respective inputs? When trying:

<label for="field" >{{item|uppercase}}:</label>
<input id="field" [value]="item"/>

Angular simply duplicates the for and id attributes, causing all labels to point to the first input field.

Is there a method to utilize Angular's component identity, or is one required to develop a unique identifier manually, ensuring uniqueness of the ID?

The limitation of not being able to nest the input within the label exists due to CSS restrictions that prevent this structure alteration. However, the desire for improved usability through proper labeling remains.

Answer №1

When dealing with unique items, it is recommended to approach it like this:

<label [for]="item" >{{item|uppercase}}:</label>
<input [id]="item" [value]="item"/>

By doing so, each id and for will be distinct, ensuring that the label functions correctly.

Check out the demo for a visual representation.

If you find yourself needing to generate unique IDs, consider using shortid.

Answer №2

If you want to experiment, consider trying out the following code snippets:

 <div class='form'>
      <ng-container *ngFor="let item of items">
        <label for="{{item}} + 'field'" >{{item|uppercase}}:</label>
        <input id="{{item}} + 'field'" [value]="item"/>
      </ng-container>
 </div>

Alternatively, you can utilize the ngfor index in case your items are not distinct:

<div class='form'>
  <ng-container *ngFor="let item of items; let i = index">
    <label for="{{i}} + 'field'" >{{item|uppercase}}:</label>
    <input id="{{i}} + 'field'" [value]="item"/>
  </ng-container>
</div>

Check out the DEMO here

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

The process of sending parameters to an API in ReactJS: a guide

My objective is to target .....the values originating from login (can be anything)-> for example email:'[email protected]' password:'12345678' I am required to extract the username until "@" and use it as a username i ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

Tips for incorporating 'and' in the 'on' clause of 'join' in knex.js

I need assistance implementing the following SQL code in knex.js: select c.id,c.parent_id,c.comment,u.username,c.postid from comments as c join post_details as p on (p.id = c.postid and c.postid=15)join users as u on (u.id = c.userid); I attempt ...

Instructions on how to extract a specific timestamp from a video and utilize it to initiate an event

Is there a way to trigger an event or animation at a specific time in a video or frame of the video? For instance, I want text to appear when a video reaches 30 seconds. I've experimented with currentTime, tried using loadeddata, and attempted to u ...

Need a tool for validating forms?

I am currently facing some confusion with the UI Validation plugin that we are using. Within our application, we employ Spring MVC, Jquery & Bootstrap. As we delve into UI development, we have encountered uncertainty in selecting an appropriate Validation ...

npm: generate new script directive

When I start up my NodeJs (ES6) project, I usually enter the following command in the console: ./node_modules/babel/bin/babel-node.js index.js However, I wanted to streamline this process by adding the command to the scripts section of my package.json fi ...

What is the best way to retrieve the array of triangles used to construct the 3D object?

I am trying to retrieve the array of triangles from the geometry object, but I am having trouble locating it. It seems that .faces in the object are not actually triangles. For example, when creating a cube, a face is structured like this: "faces": [{ ...

dynamically assigning a style attribute based on the dimensions of an image retrieved from a URL

My aim is to determine whether or not I should use an image based on its dimensions. To achieve this, I came across a function on stack overflow that can retrieve the dimensions of an image just by using its URL. Here is the code snippet they provided: f ...

Tips on modifying the selected type key name through Pick?

I currently have this structure: type Product = { name: string } and I am looking to extract the name property and use it in a different type declaration like so: type NewProduct = Pick<Product, 'name'> Now, I want to rename name as new ...

Exploring JSON data through key-value pairs

When faced with a de-serialized JSON object that has an arbitrary structure and mixed value types... var data = { 'a':'A1', 'b':'B1', 'c': [ {'a':'A2', 'b':true}, ...

Implementing autocomplete feature with JQuery by using a handler

I am currently working on developing a search box with autocomplete functionality and utilizing a handler for this purpose. While I have successfully retrieved all the words from the database, I am facing difficulties in displaying them. Here is the jQuer ...

What is preventing me from using JavaScript to generate labels?

My current project involves creating dynamic input fields to filter products by color. I initially attempted static checkbox inputs for this purpose, which worked fine. Now, I want to achieve the same functionality but dynamically through JavaScript. Inste ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

When using the Node JS driver to find elements by their class name and retrieve the text, an error is encountered

While working on Selenium tests, I am seeking feedback and the closest solution I have found is using: driver.findElement(By.className('classname')).getText(); However, in order to make it more efficient, I need to find all elements with the sa ...

Challenges with handling callbacks in Javascript

I'm currently working on creating a user-friendly GUI using the w2ui library, but I've encountered an issue with integrating a toolbar into my main layout. The problem arises when the toolbar is added before the layout is fully constructed. Sinc ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Can a React component be configured to show only a specific array key when returning an array?

Just diving into the world of react and experimenting with different approaches to understand how I can transition into this new architecture. Currently, I have a basic component where I am returning an array of elements (mainly for testing purposes): cl ...

Unlocking the Power of Session Variables in AngularJS using Ui-router

Currently, I am utilizing Angular to manage routes. On the server side, Passport is being used so that I can access the user session variable req.user in my views. However, when dealing with a route rendered by ui-router, my req.user ends up being undefine ...

What can be done to ensure that the value from a promise is retained and available for use in

Currently, I am executing a database query and then manipulating the data to obtain a single numeric value. This value is essential for use in a subsequent array. The current definition of the array appears as follows (see below). The issue at hand is tha ...