Reputation: 1694
I have a book modal, which has a name and enable flag. If the book is enabled I need to show a buy button in the view.
Sample code:
Books.ts
export class Book{
Name:string;
IsEnable:boolean;
}
books.component.ts
...
books = [{"Name":"A", "IsEnable":"True"},{"Name":"B", "IsEnable":"False"}];
....
getEligibleBooks(book){
console.log(book);
return book.IsEnable;
}
books.component.html
<div *ngFor="let book of books">
<button *ngIf="getEligibleBooks(book)"
class="link-button" style="display: inline-block"
(click)="addEvent(true)"><i class="add-circled"></i>
Buy
</button>
</div>
Issue: I have only two books but when I run the code, I'm getting multiple logs in the console. The above code is just a sample. The real code has api calls inside that getEligible method. And for two books, that method is calling endlessly. What am I doing wrong?
Upvotes: 0
Views: 61
Reputation: 21
It happens since the change detection loop calls your function several times. Why not use
<button *ngIf="book.isEnable" ... >
Or you need to do something additional actions when your books are being displayed?
Read more about change detection in angular
Upvotes: 0
Reputation: 12960
This is normal, you are getting these logs whenever a change detection cycle runs in your angular app to see if those two books changed, if yes then update the view. Change detection cycle events can happen on may cases most common of which are browser events like, click, scroll, ajax requests, timer events etc. This is the reason why we should write as less code as possible in property getters.
Upvotes: 3