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>