2017-02-05 65 views
1

我有一个包含的services
数组对象networkInterface现在我想打一个复选框,输入反射特定service_idservices阵列networkInterface的存在Angular2 - Array.prototype.filter()模板

的`接口JSON例如:

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

通常(在打字稿)这将与进行

将返回null或对象,但我怎么能做到这一点在我的HTML模板?当我试图把它像这样:

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

我得到这个错误:

Parser Error: Bindings cannot contain assignments at column 38 in [networkInterfaces.services.filter(i => i.id == service.id)[0]]

任何帮助将是非常赞赏。

回答

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)"> 
+1

是,其实这是一个非常糟糕的主意,我终于做到了在一个完全不同的方式感谢了很多。 –