Angular2 click event not firing
11,160
Solution 1
I've fixed it! It's similar to this question. It generated new array each time. So angular can't bind an event to array item. @Günter Zöchbauer, it should be familiar to you.
Solution 2
I think the problem is function changePage() has an argument of type IPage and you pass a number
public changePage(page: IPage) {
this.currentPage = page.number;
this.pageChanged.emit(null);
};
change it to
public changePage(num: number) {
this.currentPage = num;
this.pageChanged.emit(null);
};
Author by
Sergеу Isupov
Updated on June 04, 2022Comments
-
Sergеу Isupov almost 2 years
I'm trying to implement custom pagination component. This is template.
<div *ngIf="totalItems != 0"> <ul class="pagination"> <li *ngFor="let page of pages" [ngClass]="{'active': currentPage == page.title}"> <a (click)="changePage(page)">{{page.title}}</a> </li> </ul> <select> <option *ngFor="let size of pageSizes">{{size}}</option> </select> </div>
Component code:
@Component({ selector: 'pager', templateUrl: 'templates/pager.component.html', styleUrls: ['styles/pager.component.css'] }) export class PagerComponent { @Input() totalItems: number = 0; @Input() lastText: string = "»"; @Input() firstText: string = "«"; @Input() nextText: string = "›"; @Input() prevText: string = "‹"; public currentPage: number = 1; pageSizes: Array<number> = [10, 15, 30]; public currentSize: number = this.pageSizes[0]; @Output() pageChanged = new EventEmitter(); get pages(): Array<IPage> { var list = new Array<IPage>(); let pageCount = Math.ceil(this.totalItems / this.currentSize); let start = Math.max(this.currentPage - 1, 1); let end = Math.min(this.currentPage + 2, pageCount); list.push({ title: this.firstText, number: 1 }); list.push({ title: this.prevText, number: this.currentPage - 1}); for (let i = start; i <= end; i++) { list.push({ title: String(i), number: i }); } list.push({ title: this.nextText, number: this.currentPage + 1}); list.push({ title: this.lastText, number: end}); return list; } public changePage(page: IPage) { this.currentPage = page.number; this.pageChanged.emit(null); }; public resetCurrentPage(): void { this.currentPage = 1; } }
I was using simple array of numbers. Then I wanted to add Last/Firts buttons. I wrote interface that contains two properties title and page number. Now click event doesn't work. What's wrong with my code?
-
Sergеу Isupov over 7 yearsI'm sorry, I forgot to change the template. And it doesn't work this way as well.
-
Ashish Gupta about 7 yearsI'm having the same problem. Would be great if you could tell how did you solved it?
-
Sergеу Isupov about 7 yearsI can't remember details of implementation, just try to save an array in your class field and return it in a property. Please, see the link in my answer.