如何将动态创建的复选框列表与数据库值进行比较?
如果在我的数据库中的值不是null,它是一个复选框。
这就是我生成复选框的方式。我已经尝试了一些ngModel
,但我不知道如何处理这个。
<div class="list-container">
<ng-container *ngFor="let char of allATypes">
<mat-checkbox [(ngModel)]="char.checked"> {{char.bezeichnung}} </mat-checkbox>
</ng-container>
</div>
我的目标是这样的伪代码if(aType.allgemeinesMerkmal.bezeichnung) { char.checked = true) }
我该如何处理?
你差不多完成了,只要确保你将ngModel
绑定到正确的属性。
- 使用
*ngFor
循环遍历组件模板中的源数组。 - 为每个项目添加一个
checkbox
,并将其绑定到持有checked
指示器的属性,使用ngModel
。 - 如果您想再次返回更改的复选框(选中/未选中)到服务器,您必须使用双向绑定
[(ngModel)]="...."
,否则您只能使用单向绑定[ngModel]="..."
component.ts
// I used this static data, but you should use the data that comes from the server.
allATypes = [
{
title: 'Test 1',
enabled: true,
},
{
title: 'Test 2',
enabled: false,
},
{
title: 'Test 3',
enabled: true,
},
];
onSubmit() {
console.log(this.allATypes);
// here you can send the updated data to the server.
}
component.html
<ng-container *ngFor="let item of allATypes">
<mat-checkbox [(ngModel)]="item.enabled">{{ item.title }} </mat-checkbox>
</ng-container>
<button (click)="onSubmit()">Submit</button>
这是一个工作的StackBiltz演示。
您可以通过API点击:
<div class="list-container">
<ng-container *ngFor="let char of allATypes">
<mat-checkbox (click)="check_id_db(char.id)">
{{char.bezeichnung}}
</mat-checkbox>
</ng-container>
</div>
在你的.ts
文件中,当你注入了service:
constructor(private apiService: ApiService) { }
点击HTTP:
check_id_db(id){
this.apiService.check_val(id).subscribe(res=>{
console.log.(res);
});
}