Change view properties based on output of function


In my nativescript-angular app I display a list of data returned from the server. I show the results in a Listview. As each item is displayed in the list I run a function checkIfAdded(item). This function looks at each data item and for each item computes an “isAdded” boolean property and returns either true or false. Based on the result of this function I want to modify 3 properties for the button being displayed as follows: 1. I want to append a CSS class to the button 2. I want to change the displayed text of the button 3. I want to change the function that is executed by the button.

Currently I am doing this as shown in the code below:

 <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] =></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)">

While this way works in the code, I am calling the same a function in the view property binding and calling the same function thrice!!. This is also seems to be causing change detection to run multiple times each time i trigger a change, for example by tapping the button. Is there a better way to bind the 3 properties for the buttons that I show below each item in the list view. Thanks


I’d enrich the items in searchResults when the data comes back from the server, once, in your Component. Just set a boolean property on those items that your view can look at.

Also, that conditional css class logic can be simplified a bit. Assuming you have an item.added property, that would look like this: [class.remove-button]="item.added".


Thanks @Eddy. This works much better!