簡體   English   中英

如何在Angular中將標簽與標簽外的表單字段相關聯?

[英]How can I associate labels with form fields outside them in Angular?

假設我正在* ngFor循環中創建標簽和表單字段,如下所示:

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>

(在StackBlitz上查看它: https ://stackblitz.com/edit/angular-ptwq6t)

有沒有一種方法可以將這些“動態”標簽和輸入彼此清晰地關聯起來? 如果我做:

<label for="field" >{{item|uppercase}}:</label>
<input id="field" [value]="item"/>

Angular只是逐字重復forid屬性,並且所有標簽都指向第一個輸入字段。

是否可以使用某種方式使用Angular的組件標識,或者我是否堅持自己生成UUID,或者自己保證ID的唯一性?

我不能將輸入內容嵌套在標簽內,因為我必須重用一些已經實現的CSS,但這些CSS並不需要這種結構,但是仍然希望擁有合適的標簽能帶來更好的可用性。

鑒於items是唯一的,您可以肯定地做到這一點:

<label [for]="item" >{{item|uppercase}}:</label>
<input [id]="item" [value]="item"/>

這樣,每個idfor都將是唯一的,並且標簽將根據需要工作。

這是演示

如果您仍然需要生成唯一的ID,請查看shortid

你可以試試:

 <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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM