Angular2 将 map 的值绑定(bind)到复选框

标签 angular checkbox binding

我正在尝试将 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/

相关文章:

javascript - 尝试制作一个 html 复选框,将数字添加到输出字段

java - 仅当在 JavaFX 中禁用字段时如何绑定(bind)文本属性

angular - 使用具有链接的 firebase 值的 Angular Material mat-select 组件中的 compareWith 函数

javascript - 在 TypeScript 中使用相同的 Update 方法添加用户时设置自动 id

javascript - 复杂 else if 梯子的替代方案

javascript - CheckBoxList 控件在回发后丢失所有项目

angular - 如何处理 Angular 中的深层链接?

javascript - 计算多个面板中选中的复选框的数量,并使用 jQuery/JavaScript 在正确的面板中显示相关数量

c# - 绑定(bind) ComboBox ItemsSource 在 WPF 中不起作用

mysql - Ruby 中的绑定(bind)变量