In Angular 4 the hook ngOnChanges is not firing on input

前端 未结 2 566
别那么骄傲
别那么骄傲 2021-01-01 11:51

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

相关标签:
2条回答
  • 2021-01-01 12:28

    why are you using ngOnChanges you can simply use

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

    or

    <input [ngModel]="name" (keypress)="valuechange($event)">
    
    0 讨论(0)
  • 2021-01-01 12:40

    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.

    0 讨论(0)
提交回复
热议问题