Skip to content Skip to sidebar Skip to footer

How Can I Associate Labels With Form Fields Outside Them In Angular?

Let's say I'm creating labels and form fields in a *ngFor loop like this: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.ht

Solution 1:

Given that the items are unique, you could surely do this:

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

That way, each id and for would be unique and label would work as required.

Here is the demo.

If you anyway need to generate the unique IDs, take a look at shortid


Solution 2:

you can try:

 <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>

or use the ngfor index if your items are not unique:

<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>

DEMO


Post a Comment for "How Can I Associate Labels With Form Fields Outside Them In Angular?"