【问题标题】:Angular2 bind value of map to checkboxAngular2将地图的值绑定到复选框
【发布时间】:2017-10-20 04:29:14
【问题描述】:

我正在尝试将地图的值绑定到 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')"/>

目前没有显示错误,但似乎也没有绑定。

我通过使用(点击)机制找到了一些解决方案,但这不相关。复选框确实需要对组件更改做出反应。

有没有办法做到这一点,或者我应该使用不同的方法(也欢迎提出建议)。

谢谢

【问题讨论】:

    标签: angular checkbox binding


    【解决方案1】:

    我只能让“盒子里的香蕉”语法与 getter/setter 一起工作:

      get isPublic(): boolean {
        return this.profilType.get("public");
      }
    
      set isPublic(val: boolean) {
        this.profilType.set("public", val);
      }
    
      <input type="checkbox" [(ngModel)]="isPublic" />
    

    但是你可以像这样直接调用地图:

    <input type="checkbox" [ngModel]="profilType.get('public')" (ngModelChange)="profilType.set('public', $event)" />
    

    请注意,这些 getter 会被非常频繁地调用。如果性能是一个问题,您最好使用ngModelChange 将布尔值复制到地图/从地图复制:

      this.isPublic = true;
      this.profilType.set("public", true);
    
      public setPublic() {
        this.profilType.set("public", this.isPublic);
      }
    
    <input type="checkbox" [(ngModel)]="isPublic" (ngModelChange)="setPublic()" />
    

    【讨论】:

    • 好的,目前看来工作正常。当然,还有很多代码要写更多(map的每个条目的getter/setter)。顺便说一句,它将允许减少很多 html 代码。谢谢弗兰克莫迪卡。我的代表太低了,无法评价你,对不起。我不知道性能是否会成为这里的问题。我对此的反馈很少。
    • 我更新了我的示例以显示您可以直接调用地图:&lt;input type="checkbox" [ngModel]="profilType.get('public')" (ngModelChange)="profilType.set('public', $event)" /&gt;。更少的 getter/setter,但更多的 HTML。
    • 完美运行。起初我尝试了类似的解决方案,但我让括号 [(ngModel)] 而不是 [ngModel]。对于像我这样的初学者来说,它导致了很多难以阅读的错误。再次感谢。
    • @chd,因为这个答案解决了你的问题,请点击答案投票下的灰色勾号接受答案:)
    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2015-03-29
    • 2015-04-07
    相关资源
    最近更新 更多