使用 ngFor 创建复选框列表 Angular

Creating a list of checkboxes with ngFor Angular

我有一个结构如下的对象列表:

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

我正在尝试创建一个复选框列表 angular,如下所示:

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

复选框本身确实显示了,但我无法获取要与每个复选框一起显示的对象的名称。我做错了什么?

您需要将 *ngFor 放在容器上以使范围变量在其中可见。这里我用的是div,大家可以随便用

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox"> {{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 的复选框,如下所示。

<form>
   <div *ngFor="let object of objects">
      <input type="checkbox" [checked]="object.checked"> {{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>