0

在我的nativescript-angular應用程序中,顯示從服務器返回的數據列表。我在Listview中顯示結果。由於每個項目都顯示在列表中,我運行一個函數checkIfAdded(item)。此函數查看每個數據項,併爲每個項目計算每個項目的「isAdded」布爾屬性,併爲每個項目返回true或false。基於這個函數的結果,我想修改顯示的按鈕的3個屬性,如下所示: 1.我想追加一個CSS類到按鈕 2.我想改變按鈕的顯示文本 3。我想改變按鈕執行的功能。根據函數angular 2的輸出更改視圖屬性

目前如下面的代碼我這樣做:

<ListView row="2" *ngIf="searchItemsReturned" [items]="this.searchResults" class="list-group m-x-10" [itemTemplateSelector]="templateSelector"> 

//********* Template Type 1 **********   
<ng-template nsTemplateKey="type1" let-item="item"> 
    <StackLayout (tap)="onFeedItemSelect(item)"> 
     <Label [text] = item.name></Label> 
     <Button [ngClass]="{'remove-button': checkIfAdded(item)}" 
      class="btn-highlight btn-add m-y-1 m-r-4" row="0" 
      [text]="checkIfAdded(item) ? 'Remove' : 'Add'" 
      (tap)="checkIfAdded(item) ? removeFromList(item): addToList(item)"> 
     </Button> 
</StackLayout> 

雖然這種方式在代碼工作,我打電話同一視圖屬性的函數綁定和調用同樣的功能三次!!這也似乎導致變化檢測每次觸發更改時運行多次,例如通過點擊按鈕。有沒有更好的方法來綁定列表視圖中每個項目下面顯示的按鈕的3個屬性。 謝謝

回答

0

加載數據時計算isAdded屬性。然後在你的HTML只是使用該屬性,而不是每次調用函數:

//********* Template Type 1 **********   
<ng-template nsTemplateKey="type1" let-item="item"> 
    <StackLayout (tap)="onFeedItemSelect(item)"> 
     <Label [text] = item.name></Label> 
     <Button [ngClass]="{'remove-button': item.isAdded}" 
     class="btn-highlight btn-add m-y-1 m-r-4" row="0" 
     [text]=" item.isAdded ? 'Remove' : 'Add'" 
     (tap)=" item.isAdded ? removeFromList(item): addToList(item)"> 
     </Button> 
</StackLayout>