Angular ngOnChanges hook学习笔记
只有這三種事件才會導致Angular視圖的更新,都是異步事件。
- Events:如 click, change, input, submit 等用戶事件
- XMLHttpRequests:比如從遠端服務獲取數據
- Timers: 比如 JavaScript 的自有 API setTimeout(), setInterval()
https://angular.io/guide/lifecycle-hooks
Respond when Angular sets or resets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.
Note that this happens very frequently, so any operation you perform here impacts performance significantly.
看一個例子:子組件實現了Change detect hook:
子組件的bankName, 綁定到了父組件的bankName屬性上:
完整源代碼:
export class BankAccount implements OnChanges{ngOnChanges(changes: SimpleChanges): void {debugger;}// This property is bound using its original name.@Input() bankName: string;// this property value is bound to a different property name// when this component is instantiated in a template.@Input('account-id') id: string;// this property is not bound, and is not automatically updated by AngularnormalizedBankName: string; }@Component({selector: 'app',template: `<bank-account [bankName]="bankName" account-id="4747"></bank-account>` }) export class App implements OnInit, AfterViewInit{_bankName = 'Jerry';ngAfterViewInit(): void {this._bankName = 'Jerry2';}get bankName(){debugger;return this._bankName;}ngOnInit(): void {debugger;}}父組件的bankName,在OnInit和OnAfterViewInit時都會變化,這也會觸發子組件的ngOnChange接口:
第一次觸發:
然后父組件的模板第二次被渲染,bankName變成Jerry2:
此時再次refreshView之后,最新的Jerry2和之前的Jerry都記錄在SimpleChange數據結構里了:
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的Angular ngOnChanges hook学习笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular set函数和Compon
- 下一篇: 一般存款账户和基本存款账户的区别