Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
deepthan opened this issue Jun 17, 2020 · 0 comments
Open

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

deepthan opened this issue Jun 17, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

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;
  }
}

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant