我是Angular2 / 4的新手 . 我创建了一个带有输入字段的基本组件 . 用户输入将反映在绑定到用户输入的其他组件中 . 现在我想设置一个值更改的一般监听器 .
我认为OnChanges钩子是完美的解决方案,但是从未调用过ngOnChanges方法 . 难道我做错了什么?
任何暗示赞赏......
import { Component, Input, SimpleChanges, OnChanges } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<input [(ngModel)]="name">
<input [(ngModel)]="name">
<h1>{{name}}</h1>
`,
})
export class AppComponent implements OnChanges {
@Input() name: String = "abc"
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
console.log('on change', changes)
}
}
2 回答
每次组件属性在内部更改时都不会调用
ngOnChanges
. 当父组件的数据绑定将新值推送到子组件时,它会被调用 . 所以如果你的父组件有当
parentValue
更改时,子组件的@Input() name
将更改,这将触发ngOnChanges
拿一个look at the docs:
要在表单输入发生更改时收到通知,从长远来看,最好的方法是学习Reactive Forms,因为它们会让您在组件中创建
FormControl
对象,并展示每次表单值更改时都会发出的非常简单的observable .如果您希望坚持使用模板驱动的表单,则可以绑定到输入的
keypress
或keyup
事件以触发您想要在更改时运行的任何逻辑 .为什么你使用ngOnChanges你可以简单地使用
要么