【问题标题】:Detect changes @Input binding in angular检测角度变化@Input绑定
【发布时间】:2019-10-04 23:36:03
【问题描述】:

我需要检测@Input绑定角度的值变化,并在值变化时执行一个函数

@Component({
  selector: 'my-comp',
  ...
})
...
@Input() myValue

//detect myValue changes

<my-comp [myValue]= "val"></my-comp>

val 发生变化时,我需要执行一些代码组件类。

【问题讨论】:

标签: angular


【解决方案1】:

您可以在 Angular 中使用 ngOnChange 生命周期挂钩来获得高级功能。

export class MyCoponent implements OnChanges{

@Input() myValue

ngOnChanges(changes:SimpleChange){

 //current value
 let currentVal= changes.myValue.currentValue
 // previouse value
 let prev = changes.previousValue
}

ngOnChanges 函数在myValue 发生任何变化时执行

【讨论】:

    【解决方案2】:

    您可以在这里简单地使用set,如下所示:

    _myvalue: any;
    @Input() set myValue(value: any) {
        ... // Your code goes here
        this._myvalue = value;
    }
    

    现在,每次您在模板中为 myValue 赋值时,都会调用 setter 并执行您的代码。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-22
      • 2021-06-17
      • 2023-03-24
      • 2021-08-07
      • 2018-10-24
      • 1970-01-01
      • 2018-08-25
      • 2017-06-03
      相关资源
      最近更新 更多