如何从哈希图初始化复选框(Angular 2) [英] How to initialize checkbox from hashmap (Angular 2)
问题描述
我们如何初始化和操作复选框值?我看了很多例子,但是还没有任何例子可以解决.
How can we initialize and manipulate a check box value? I've looked at quite a number of examples, but haven't been able to get any to work.
我正在尝试提供一个N x M
表,其中行表示任务,而列表示学生.想法是,选中表中的复选框之一将任务分配给学生.
I'm trying to present a N x M
table where the rows represent tasks, and the columns students. The idea is that checking one of the check-boxes in the table assigns a task to a student.
有一个打字稿哈希图,其中包含所有checkboxes
的值;
There is a typescript hash map which contains the value of all the checkboxes
;
assigned : { [key:string]:boolean; } = {};
哈希键是:
var key = a.TaskId + '_' + a.StudentId;
该表是使用嵌套的ngFor生成的:
The table is generated with a nested ngFor:
<tr *ngFor="let t of tasks">
<td>Task Name for task... {{t.taskId}} </td>
<td *ngFor="let s of students">
<input type="checkbox" name=#{{t.TaskId}}_{{s.StudentId}} change="onAssignmentChange(t,s)" [checked]="cbValue(t, s)">
</td>
</tr>
cbValue(t, s)
在下面:
cbValue(taskItem, studentItem) {
var key = taskItem.TaskId + '_' +studentItem.StudentId;
return this.assigned[key];
}
这行不通,无论哈希中的值是什么,表中的所有复选框都未选中.
This doesn't work, all the checkboxes in the table come up unchecked, no matter what the values in the hash.
我也尝试过:
<input type="checkbox" change="onAssignmentChange(t,s)" [checked]="cbValue(t, s)">
<input type="checkbox" change="onAssignmentChange(t,s)" [(ngModel)]={{t.TaskId}}+'_'+{{s.StudentId}} >
<input type="checkbox" change="onAssignmentChange(t,s)" [(ngModel)]="assigned[t.TaskId"+'_'+"s.StudentId"]>
没有一个起作用.
我似乎在这里很暗. onAssignmentChange
也不会触发,控制台中没有错误.
I seem to be quite in the dark here; onAssignmentChange
doesn't get triggered either, there are no Errors in console.
也是
... name=#{{t.TaskId}}_{{s.StudentId}} ...
这应该是本地目标吗?
预先感谢
推荐答案
这很简单,因为我们将直接绑定到assigned
对象,因为我们使用的是JavaScript的方括号属性访问器,所以我们也得到了通过模板对属性进行免费的动态实例化(可能有点脏,但功能强大).此外,以后无论在何处进行处理,都假定缺少的值为false:
This is fairly trivial as we're just going to bind straight to the assigned
object, since we're using JavaScript's bracket property accessor we also get a free dynamic instantiation of the property through the template (dirty, maybe, but powerful). Additionally, wherever you're processing this later assume that a missing value is false:
模板
<tr *ngFor="let t of tasks">
<td>Task Name for task... {{t.taskName}} </td>
<td *ngFor="let s of students">
<input type="checkbox" name="{{t.taskId}}_{{s.studentId}}" [(ngModel)]="assigned[t.taskId + '_' + s.studentId]">
</td>
</tr>
下面是一个演示者: http://plnkr.co/edit/9RorhJnv42cCCJanWb80L?p =预览
这篇关于如何从哈希图初始化复选框(Angular 2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!