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:
<divclass='form'><ng-container *ngFor="let item of items"><labelfor="{{item}} + 'field'" >{{item|uppercase}}:</label><inputid="{{item}} + 'field'" [value]="item"/></ng-container></div>
or use the ngfor index if your items are not unique:
<divclass='form'><ng-container *ngFor="let item of items; let i = index"><labelfor="{{i}} + 'field'" >{{item|uppercase}}:</label><inputid="{{i}} + 'field'" [value]="item"/></ng-container></div>
Post a Comment for "How Can I Associate Labels With Form Fields Outside Them In Angular?"