使用ngFor Angular创建复选框列表
我有一个如下结构的对象列表:使用ngFor Angular创建复选框列表,angular,checkbox,angular-template,angular-ngfor,Angular,Checkbox,Angular Template,Angular Ngfor,我有一个如下结构的对象列表: [{item},{item},{item}] 我正在尝试创建一个复选框列表,其中包含以下内容: {{object.name} 复选框本身确实会显示,但我无法获取每个复选框显示的对象的名称。我做错了什么?您需要在容器上放置*ngFor,使范围变量在其中可见。这里我使用了div,但是您可以使用任何您想要的东西 {{object.name} 您需要在容器上放置*ngFor,使范围变量在容器中可见。这里我使用了div,但是您可以使用任何您想要的东西 {{objec
[{item},{item},{item}]
我正在尝试创建一个复选框列表,其中包含以下内容:
{{object.name}
复选框本身确实会显示,但我无法获取每个复选框显示的对象的名称。我做错了什么?您需要在容器上放置
*ngFor
,使范围变量在其中可见。这里我使用了div
,但是您可以使用任何您想要的东西
{{object.name}
您需要在容器上放置*ngFor
,使范围变量在容器中可见。这里我使用了div
,但是您可以使用任何您想要的东西
{{object.name}
对象变量仅存在于ngForOf
的上下文中,在您的情况下,这就是
元素的上下文
您可以将
包装在ng容器
元素中,并将ngForOf
绑定到最后一个。像这样:
<form>
<ng-container *ngFor="let object of objects">
<input type="checkbox"> {{object.name}}
<ng-container>
</form>
{{object.name}
使用这种方法,生成的HTML是相同的,因为ng容器元素被剥离。对象
变量只存在于ngForOf
的上下文中,在您的情况下,这是
元素的上下文
您可以将
包装在ng容器
元素中,并将ngForOf
绑定到最后一个。像这样:
<form>
<ng-container *ngFor="let object of objects">
<input type="checkbox"> {{object.name}}
<ng-container>
</form>
{{object.name}
使用这种方法,生成的HTML是相同的,因为ng容器元素被剥离了。您可以使用带有*ngFor的复选框,如下所示
<form>
<div *ngFor="let object of objects">
<input type="checkbox" [checked]="object.checked"> {{object.name}}
<div>
</form>
{{object.name}
您可以使用带有*ngFor的复选框,如下所示
<form>
<div *ngFor="let object of objects">
<input type="checkbox" [checked]="object.checked"> {{object.name}}
<div>
</form>
{{object.name}
我必须确保标签中的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>
{{detectionSource.name}
我必须确保标签中的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>
{{detectionSource.name}
它可以工作,但它确实创建了一些样板。我想这是唯一的出路。您认为我的示例不起作用是因为Angular没有访问object.name变量的权限吗?是的,outsideinput
不可见。它起作用,但确实创建了一些样板文件。我想这是唯一的出路。您是否认为我的示例不起作用,因为Angular没有访问object.name变量的权限?是的,outsideinput
不可见。