I am pretty new to Angular2/4. I have created a basic component with an input field. The user input will be reflected in the other components that are bound to the user inpu
why are you using ngOnChanges you can simply use
<input [(ngModel)]="name" (input)="valuechange($event)">
or
<input [ngModel]="name" (keypress)="valuechange($event)">
ngOnChanges
is not called every time a component property changes internally. It gets called when the databinding from the parent component pushes a new value into the child component. So if your parent component has
<child-comp [name]="parentValue"></child-comp>
When parentValue
changes, the child component's @Input() name
will change and that will trigger ngOnChanges
Take a look at the docs:
ngOnChanges
Respond when Angular (re)sets data-bound input properties...Called before ngOnInit() and whenever one or more data-bound input properties change.
To be notified when your form inputs change, in the long run the best approach is to learn Reactive Forms because they make you create the FormControl
objects in your component and expose a very simple observable that emits every time the form value changes.
If you wish to stick with template-driven forms, you can bind to the input's keypress
or keyup
event to fire whatever logic you want to run on change.