Angular2单击事件未触发

时间:2016-09-27 09:20:41

标签: events angular typescript

我正在尝试实现自定义分页组件。这是模板。

<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({
    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;
    }
}

我使用简单的数字数组。然后我想添加Last / Firts按钮。我写了包含两个属性标题和页码的界面。现在点击事件不起作用。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

我认为问题是函数changePage()有一个IPage类型的参数,你传递一个数字

 public changePage(page: IPage) {
    this.currentPage = page.number;
    this.pageChanged.emit(null);
};

将其更改为

 public changePage(num: number) {
    this.currentPage = num;
    this.pageChanged.emit(null);
};

答案 1 :(得分:0)

我修好了!它与this question类似。它每次都生成新的数组。因此angular不能将事件绑定到数组项。 @GünterZöchbauer,你应该对它很熟悉。