2017-02-05 64 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

是,其實這是一個非常糟糕的主意,我終於做到了在一個完全不同的方式感謝了很多。 –