【问题标题】:Change view properties based on output of function angular 2根据函数 angular 2 的输出更改视图属性
【发布时间】:2017-08-17 14:38:48
【问题描述】:

在我的 nativescript-angular 应用程序中,我显示了从服务器返回的数据列表。我在 Listview 中显示结果。当每个项目都显示在列表中时,我运行一个函数 checkIfAdded(item)。此函数查看每个数据项,并为每个项目计算每个项目的“isAdded”布尔属性,并为每个项目返回 true 或 false。根据此函数的结果,我想修改正在显示的按钮的 3 个属性,如下所示: 1. 我想在按钮上附加一个 CSS 类 2.我想改变按钮的显示文字 3. 我想改变按钮执行的功能。

目前我正在这样做,如下面的代码所示:

  <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 个属性。 谢谢

【问题讨论】:

    标签: angular angular2-template angular2-nativescript angular2-changedetection


    【解决方案1】:

    加载数据时计算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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      相关资源
      最近更新 更多