In Angular 4, the ngOnChanges hook doesn't trigger login

I am new to Angular2 / 4. I created a base component with an input field. User input will be reflected in other components tied to user input. Now I want to configure the general listener to change the value.

I thought the OnChanges hook would be the perfect solution. But the ngOnChanges method will never be called. Am I on the wrong track here or what am I doing wrong?

Any hint appreciated ...

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) } } 
+7
angular
source share
2 answers

ngOnChanges not called every time a component property is changed internally. It is called when data binding from the parent component pushes the new value into the child component. Therefore, if your parent component has

 <child-comp [name]="parentValue"></child-comp> 

When parentValue changes parentValue child component of @Input() name will change and this will call ngOnChanges

Take a look at the docs :

ngOnChanges

Answer when Angular (re) sets the data entry properties ... Called before ngOnInit () and when one or more data entry properties changes.

To receive notifications of changes in your forms, in the end, the best approach is to study Reactive Forms , since they force you to create FormControl objects in your component and set up a very simple observation that is emitted each time the form value changes.

If you want to stick to template-driven forms, you can bind to a keypress or keyup input event to trigger any logic that you want to trigger when changing.

+12
source share

why are you using ngOnChanges, you can just use

  <input [(ngModel)]="name" (input)="valuechange($event)"> 

or

 <input [ngModel]="name" (keypress)="valuechange($event)"> 
+3
source share

All Articles