我目前正在學習角度并嘗試創建一個簡單的分頁。代碼非常簡單但令人困惑,代碼中的值總是落后于模板上顯示的值。模板上顯示的值是正確的。
父組件
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentPage = 1;
totalPage = 3;
loadPage(event: string) {
if (event === 'next') {
this.currentPage = 1;
}
else {
this.currentPage -= 1;
}
}
}
父 HTML
<p>Parent</p>
<app-pagination [currentPage]="currentPage"
[totalPage]="totalPage"
(pagingEvent)="loadPage($event)">
</app-pagination>
子組件
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-pagination',
templateUrl: './pagination.component.html',
styleUrls: ['./pagination.component.scss'],
})
export class PaginationComponent implements OnInit {
@Input() currentPage!: number;
@Input() totalPage!: number;
@Output() pagingEvent = new EventEmitter<string>();
constructor() { }
ngOnInit() {
}
gotoPage(direction: string) {
console.log('Current Page value:', this.currentPage);
this.pagingEvent.emit(direction);
}
}
子 HTML
<ul>
<li (click)="gotoPage('previous')">« Previous</li>
<li class="total">{{ currentPage }}/{{ totalPage }}</li>
<li (click)="gotoPage('next')">Next »</li>
</ul>
這是結果的螢屏截圖

如您所見,在模板上顯示為 3/3,但 console.log 顯示的是 2 而不是 3
即使您在函式中傳遞變數,它也總是在模板上顯示的值后面 1 個數字。
<li (click)="gotoPage('next', currentPage)">Next »</li>
為什么會發生這種情況以及如何解決?
謝謝
uj5u.com熱心網友回復:
這是正確的,你的代碼是這樣作業的:
假設頁面當前是 3 中的 2 作為起點。
- 在子組件上單擊下一步
- 子組件呼叫“goToPage”
- goToPage console.logs 當前頁面為 2
- goToPage 發出我們要去下一頁
- 父級讀取此發射并轉到下一頁(例如到 3)
- 父級將當前頁面(現在是 3 個)BACK 傳遞給子組件
- 子組件更新 UI 以顯示 3
唯一發生的 console.log 是在頁面增加之前,而不是之后。所以這是按預期作業的。
如果我是你,我會像這樣改造我的代碼。
從'@angular/core'匯入{組件,輸入,OnInit,輸出,EventEmitter};
@Component({
selector: 'app-pagination',
templateUrl: './pagination.component.html',
styleUrls: ['./pagination.component.scss'],
})
export class PaginationComponent implements OnInit {
@Input() startingPage: number;
@Input() currentPage!: number;
@Input() totalPage!: number;
@Output() pagingEvent = new EventEmitter<number>();
constructor() { }
ngOnInit() {
currentPage = startingPage;
}
gotoPage(direction: string) {
if (event === 'next') {
this.currentPage = 1;
}
else {
this.currentPage -= 1;
//What if page is 0 etc?
}
this.pagingEvent.emit(this.currentPage);
console.log(this.currentPage);
}
}
分頁控制器應該完全控制當前頁面是什么。不僅因為這意味著每個父母都不必管理它。但是因為在您的代碼中,如果您不小心,您可能會以無限回圈結束(見過很多次),因為您不斷傳遞可能觸發更多更改等的當前頁面。
相反,分頁組件應該向上發出當前頁面的內容(例如,父級可以通過資料進行分頁)。但除此之外,它不必擔心我們前進的方向等。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450137.html
標籤:有角度的
