簡體   English   中英

使用 ngFor Angular 創建復選框列表

[英]Creating a list of checkboxes with ngFor Angular

我有一個結構如下的對象列表:

[{item},{item},{item}]

我正在嘗試創建一個帶有角度的復選框列表,如下所示:

<form>
     <input *ngFor="let object of objects" type="checkbox"> {{object.name}}
</form>

復選框本身確實出現了,但我無法獲得每個復選框顯示的對象名稱。 我究竟做錯了什么?

您可以將復選框與 *ngFor 一起使用,如下所示。

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox" [checked]="object.checked"> {{object.name}}
   <div>
</form>

object變量僅存在於ngForOf的上下文中,在您的情況下,這是<input>元素的上下文。

您可以將<input>包裹在ng-container元素內,並將ngForOf綁定到最后一個。 像這樣:

<form>
   <ng-container *ngFor="let object of objects">
      <input type="checkbox"> {{object.name}}
   <ng-container>
</form>

使用這種方法,生成的 HTML 是相同的,因為 ng-container 元素被剝離了。

您需要將*ngFor放在容器上以使范圍變量在其中可見。 這里我使用了div ,但你可以使用任何你想要的東西。

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox"> {{object.name}}
   <div>
</form>

我必須確保標簽中的for屬性與輸入 id 相同:

在此處查看片段

 <div class="m-checkbox-list">
   <label *ngFor="let detectionSource of detectionSources" for="detectionSource_{{detectionSource.id}}" class="m-checkbox">
    <input id="detectionSource_{{detectionSource.id}}" type="checkbox" name="detectionSource_{{detectionSource.name}}" [(ngModel)]="detectionSource.isSelected">
                                    {{detectionSource.name}}
    <span></span>
   </label>
 </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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