deepthan/blog-angular

Angular 组件监听传过来值变化的若干姿势

deepthan opened this issue · 0 comments

1. Onchanges生命周期

import { Input, OnChanges, SimpleChanges } from '@angular/core';
...
export class xxx implements OnChanges {
  @Input() title: string;
  
  ngOnChanges(sc: SimpleChanges) {
    if('title' in sc){ // 需要做存在判断才能使用
        // sc.title.currentValue --> 最新的值,做一些处理逻辑
    } 
  }
}

2. get、set

import { Input } from '@angular/core';
...
export class xxx implements OnChanges {
   _title: string;
  @Input()
  get title() {
    return this._title;
  }
  set title(value) {
    // 做一些处理逻辑
    this._title = value;
  }
}

==传过来的值若为引用类型,只是改变属性,引用不变上述方法均不会触发,建议传过来的时候深拷贝一下==