问题
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.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.com/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 component 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 comes from having a proper label.
回答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
回答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
来源:https://stackoverflow.com/questions/53406626/how-can-i-associate-labels-with-form-fields-outside-them-in-angular