Reputation:
On my site I have two buttons, next and previous to navigate between newer (next) and older (previous) items of news. I wish to prevent the next button being rendered on the page when there is no newer news available to view. To do this I used *ngIf
<a *ngIf="isNextNews()" (click)="nextNews()">< Next</a>
Here is the function to check for more recent news:
public isNextNews() {
this.findNewsInCategories();
if(typeof this.appConfigService.news[this.newsIndex-1] == 'undefined') {
return false;
}
return true;
}
This works, but not quite as well as I'd hoped. Instead of the next button always being rendered and only being removed when the check fails it re-renders every time you navigate to a newer or older news item. The functionality I'm looking for is having the next button always be rendered except for when the check fails, removing the next button from the DOM. Any ideas how I can achieve this?
Upvotes: 2
Views: 1408
Reputation: 11399
Do not use functions in template expressions (in this case *ngIf
), that is because the function will be called after each change detection. Use a variable instead.
hasNextNews:boolean = false; //use this in your view
constructor(){
}
nextNews(){
//your logic
this.isNextNews(); //added
}
isNextNews() {
this.findNewsInCategories();
this.hasNextNews = (typeof this.appConfigService.news[this.newsIndex-1] != 'undefined')
}
Html:
<a *ngIf="hasNextNews" (click)="nextNews()">< Next</a>
Upvotes: 1
Reputation: 807
Suppose you're calling loadNews()
on first page load, then it should be like
var hasNextNews = false;
public loadNews() {
## load your current news here
isNextNews();
}
and next function:
public isNextNews() {
this.findNewsInCategories();
if(typeof this.appConfigService.news[this.newsIndex-1] == 'undefined') {
this.hasNextNews = false;
}
this.hasNextNews = true;
}
html:
<a *ngIf="hasNextNews" (click)="nextNews()">< Next</a>
Upvotes: 0