简体   繁体   English

在组件模型属性上触发ngOnChanges

[英]fire ngOnChanges on component model property

On my template I have this line of code: 在我的模板上,我有这行代码:

<input name="distanceA" id="distanceA" type="number" [(ngModel)]="distanceA"/> {{distanceA}} meter

In it's component.ts file I have this: 在它的component.ts文件中我有这个:

distanceA: number;

and further on this: 并进一步:

ngOnChanges(changes: any) {
    if (changes["distanceA"] ) {
       alert(changes["distanceA"].currentValue);
    }
    if (changes["distanceB"] ) {
       alert(changes["distanceB"].currentValue);
    }
}

However the ngOnChanges event doesn't fire when typing in the inputbox. 但是,在输入框中键入时,ngOnChanges事件不会触发。 What's the reason for this? 这是什么原因? How can I make this work? 我怎样才能做到这一点? The binding itself works as I see what I type in the inputbox showing up on the page with {{distanceA}} 绑定本身就像我在输入框中输入的内容一样,显示在{{distanceA}}页面上

That's as designed. 那是设计的。 ngOnChanges isn't called when a property is modified, it's called when a bound value (bound with [distanceA]="propFromParent" ) is changed that causes the @Input() of the child component to be changed. 修改属性时不调用ngOnChanges当更改绑定值(使用[distanceA]="propFromParent"绑定)并导致更改子组件的@Input() ,将@Input()

Just change your property to a getter/setter like 只需将您的属性更改为getter / setter

_distanceA: number;
get distanceA() { return this._distanceA; }
set distanceA(val:number) { 
  this._distanceA = val; 
  alert(val);
}

You can handle it with (keypress) event. 您可以使用(keypress)事件处理它。

Short example. 简短的例子。

<input placeholder="0-99999" minlength="1" maxlength="5" name="areaCode" [(ngModel)]="number" (keypress)="validateNumber($event)" required>

validateNumber(event): boolean {
    return event.charCode >= 48 && event.charCode <= 57;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM