zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Angular ngOnChanges hook学习笔记

2023-09-14 09:04:02 时间

只有这三种事件才会导致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 Angular
  normalizedBankName: 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的原创文章,尽在:“汪子熙”: