typescript angular2 @input - 变化检测

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41726875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:10:50  来源:igfitidea点击:

angular2 @input - change detection

angulartypescriptdata-binding

提问by gka

Is there a way to listen for @Input change?

有没有办法监听@Input 的变化?

In following example, I would like to be informed whenever 'inputData' value is changed.

在以下示例中,我希望在“inputData”值更改时收到通知。

@Input() inputData: InputData;

回答by Stefan Svrkota

Yeah, you can use OnChangeslifecycle event:

是的,您可以使用OnChanges生命周期事件:

@Input() inputData: InputData;

ngOnChanges() {
    console.log(this.inputData);
}

Read more about Angular's lifecycle events here.

在此处阅读有关 Angular 生命周期事件的更多信息。

回答by yala ramesh

import { Component, Input, OnChanges, SimpleChange } from '@angular/core';


export class Demo implements OnChanges {

 @Input() inputData: InputData;
 ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {

    if (changes['inputData'] && this.inputData) {

        //your logic work when input change
    }
 }

}

回答by Bardia Rastin

you can use something like :

你可以使用类似的东西:

Input('value')
set value(val: string) {
  this._value = val;
  console.log('new value:', value); // <-- do your logic here!
}

more info available at this link

链接提供更多信息

you can also take a look at this article

你也可以看看这篇文章

回答by Pankaj Parkar

You could listen to OnChangescomponent lifecycle event inside your component

您可以在OnChanges组件内侦听组件生命周期事件

ngOnChanges(model: SimpleChanges){
   console.log(model)
}