Изменить свойства вида на основе вывода функции angular 2

В моем приложении nativescript-angular я отображаю список данных, возвращаемых с сервера. Я показываю результаты в виде списка. Поскольку каждый элемент отображается в списке, я запускаю функцию 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>

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


person Anurag    schedule 17.08.2017    source источник


Ответы (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>
person Faisal    schedule 17.08.2017