[英]How can I associate labels with form fields outside them in Angular?
假設我正在* 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>
(在StackBlitz上查看它: https ://stackblitz.com/edit/angular-ptwq6t)
有沒有一種方法可以將這些“動態”標簽和輸入彼此清晰地關聯起來? 如果我做:
<label for="field" >{{item|uppercase}}:</label>
<input id="field" [value]="item"/>
Angular只是逐字重復for
和id
屬性,並且所有標簽都指向第一個輸入字段。
是否可以使用某種方式使用Angular的組件標識,或者我是否堅持自己生成UUID,或者自己保證ID的唯一性?
我不能將輸入內容嵌套在標簽內,因為我必須重用一些已經實現的CSS,但這些CSS並不需要這種結構,但是仍然希望擁有合適的標簽能帶來更好的可用性。
你可以試試:
<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>
或使用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.