Let's say I'm creating labels and form fields in a *ngFor loop like this:
appponent.ts
export class AppComponent {
items = ['aaa', 'bbbbbb', 'ccccccccc']
}
appponent.html
<div class='form'>
<ng-container *ngFor="let item of items">
<label>{{item|uppercase}}:</label>
<input [value]="item"/>
</ng-container>
</div>
(See it on StackBlitz: )
Is there a way to cleanly associate these "dynamic" labels and inputs with one another? If I do:
<label for="field" >{{item|uppercase}}:</label>
<input id="field" [value]="item"/>
Angular just repeats the for
and id
attributes verbatim and all labels point to the first input field.
Is there some way to use Angular's ponent identity, or am I stuck with something like generating a UUID myself, or otherwise guaranteeing uniqueness of the ID myself?
I can't nest the input inside the label because I have to reuse some already implemented CSS that doesn't expect that structure, but would still like the better usability that es from having a proper label.
Let's say I'm creating labels and form fields in a *ngFor loop like this:
app.ponent.ts
export class AppComponent {
items = ['aaa', 'bbbbbb', 'ccccccccc']
}
app.ponent.html
<div class='form'>
<ng-container *ngFor="let item of items">
<label>{{item|uppercase}}:</label>
<input [value]="item"/>
</ng-container>
</div>
(See it on StackBlitz: https://stackblitz./edit/angular-ptwq6t)
Is there a way to cleanly associate these "dynamic" labels and inputs with one another? If I do:
<label for="field" >{{item|uppercase}}:</label>
<input id="field" [value]="item"/>
Angular just repeats the for
and id
attributes verbatim and all labels point to the first input field.
Is there some way to use Angular's ponent identity, or am I stuck with something like generating a UUID myself, or otherwise guaranteeing uniqueness of the ID myself?
I can't nest the input inside the label because I have to reuse some already implemented CSS that doesn't expect that structure, but would still like the better usability that es from having a proper label.
Share Improve this question asked Nov 21, 2018 at 6:48 millimoosemillimoose 40k11 gold badges87 silver badges138 bronze badges2 Answers
Reset to default 5Given 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
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