我正在尝试将 map 的值绑定(bind)到 angular2 中的 html 复选框。
this.profilType = new Map<string, boolean>();
this.profilType.set("public", true);
至
<input type="checkbox" [(ngModel)]="profilType['public']"/>
我之前尝试过这个,但它导致了错误。
<input type="checkbox" [(ngModel)]="profilType.get('public')"/>
目前没有显示任何错误,但似乎也没有绑定(bind)。
我通过使用(点击)机制找到了一些解决方案,但这不相关。复选框确实需要对组件更改使用react。
有没有办法做到这一点,或者我应该使用不同的方法(也欢迎建议)。
谢谢
最佳答案
我只能使用“banana in a box”语法来与 getter/setter 一起使用:
get isPublic(): boolean {
return this.profilType.get("public");
}
set isPublic(val: boolean) {
this.profilType.set("public", val);
}
<input type="checkbox" [(ngModel)]="isPublic" />
但是你可以像这样直接调用 map :
<input type="checkbox" [ngModel]="profilType.get('public')" (ngModelChange)="profilType.set('public', $event)" />
请注意,这些 getter 会被频繁调用。如果性能是一个问题,您最好使用 ngModelChange
将 bool 值复制到 map 或从 map 复制 bool 值:
this.isPublic = true;
this.profilType.set("public", true);
public setPublic() {
this.profilType.set("public", this.isPublic);
}
<input type="checkbox" [(ngModel)]="isPublic" (ngModelChange)="setPublic()" />
关于Angular2 将 map 的值绑定(bind)到复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44080264/