【问题标题】:Angular2 - Array.prototype.filter() in templatesAngular2 - 模板中的 Array.prototype.filter()
【发布时间】:2017-06-22 05:22:07
【问题描述】:

我有一个对象networkInterface,其中包含services的数组
现在我想做一个复选框输入,反映networkInterfaceservices 数组中存在特定的service_id

`接口的JSON示例:

[  
   {  
      "id":11,
      "name":"External Interface",
      "services":[  
         {  
            "id":1,
            "name":"Web Service"
         },
         {  
            "id":2,
            "name":"FTP Service"
         }
      ]
   }
]

现在通常(在 TypeScript 中)这将通过以下方式完成:

networkInterfaces.services.filter(i => i.id == service.id)[0]

这将返回null 或一个对象,但我怎样才能在我的html 模板中做到这一点?当我尝试这样说时:

<input type="checkbox" [(ngModel)]="networkInterfaces.services.filter(i => i.id == service.id)[0]">

我收到此错误:

解析器错误:绑定不能包含第 38 列的赋值 [networkInterfaces.services.filter(i => i.id == service.id)[0]]

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays angular data-binding angular2-template


    【解决方案1】:

    首先这样做是个坏主意。每次更改检测运行时,都会重新执行此过滤器调用。这会降低页面的性能,甚至可能变得无法使用。首选方法是为属性赋值,然后绑定到该属性。

    constructor() {
      this.prop = interfaces.services.filter(i => i.id == service.id)[0];
    }
    
    propChanged(e) {
      interfaces.services.filter(i => i.id == service.id)[0] = e;
    }
    
    <input type="checkbox" [ngModel]="prop" (ngModelChange)="propChanged($event)">
    

    【讨论】:

    • 是的,事实上这是一个非常糟糕的主意,我最终以完全不同的方式做到了,非常感谢。
    猜你喜欢
    • 2016-12-25
    • 2017-11-11
    • 2016-10-19
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多