Angular ngOnChanges hook学习笔记
只有這三種事件才會(huì)導(dǎo)致Angular視圖的更新,都是異步事件。
- Events:如 click, change, input, submit 等用戶事件
- XMLHttpRequests:比如從遠(yuǎn)端服務(wù)獲取數(shù)據(jù)
- 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.
看一個(gè)例子:子組件實(shí)現(xiàn)了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時(shí)都會(huì)變化,這也會(huì)觸發(fā)子組件的ngOnChange接口:
第一次觸發(fā):
然后父組件的模板第二次被渲染,bankName變成Jerry2:
此時(shí)再次refreshView之后,最新的Jerry2和之前的Jerry都記錄在SimpleChange數(shù)據(jù)結(jié)構(gòu)里了:
更多Jerry的原創(chuàng)文章,盡在:“汪子熙”:
總結(jié)
以上是生活随笔為你收集整理的Angular ngOnChanges hook学习笔记的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Angular set函数和Compon
- 下一篇: SAP Spartacus cxFocu