[英]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: 假设我正在* ngFor循环中创建标签和表单字段,如下所示:
export class AppComponent {
items = ['aaa', 'bbbbbb', 'ccccccccc']
}
<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 ) (在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. Angular只是逐字重复
for
和id
属性,并且所有标签都指向第一个输入字段。
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? 是否可以使用某种方式使用Angular的组件标识,或者我是否坚持自己生成UUID,或者自己保证ID的唯一性?
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. 我不能将输入内容嵌套在标签内,因为我必须重用一些已经实现的CSS,但这些CSS并不需要这种结构,但是仍然希望拥有合适的标签能带来更好的可用性。
Given that the items
are unique, you could surely do this: 鉴于
items
是唯一的,您可以肯定地做到这一点:
<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. 这样,每个
id
和for
都将是唯一的,并且标签将根据需要工作。
If you anyway need to generate the unique IDs, take a look at shortid 如果您仍然需要生成唯一的ID,请查看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: 或使用ngfor索引(如果您的商品不唯一):
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.