0
votes

https://next.plnkr.co/edit/0LHeJ3Fyz5gdjJqQ?open=lib%2Fapp.ts&deferRun=1 Here's a plunkr. It's just for example.

In real project i got something like

<input [(ngModel)]='_data.name' [name]='name' />

I pass some data for input by using ngOnInit lifehook
And i cant understand why my ngOnChanges hook doesn't trigger changes when i write something in my <input>

The _data takes data from json/server by using services http request, then i get name in my <input>, or something on
The question is: how to detect changes with ngOnChange lifehook in my situation
I try to set [name]='name' and then take it using @Input like that

@Input() name: string; 

Then in ngOnChanges

ngOnChanges(changes: SimpleChanges) {
  console.log(changes.name.currentValue);
}  

Why i do not see anything in my console? Why ngOnChanges is not working this way? I need to take value from my input, then detect it changes using ngOnChanges No errors in console, no data, just nothing, empty

2
why are you want to use ngOnChanges ?, instead listen onChange, input or keyup events on your input - Artyom Amiryan

2 Answers

0
votes

That's because the relation between two components is not well implemented.

We should have a deal firstly that @input() decorators are implementend only in a child component, that means, you have to make your changes in the father component and pass those changes to the child so it will invoke its ngOnChanges method. That is to say:

in your Father component:

@Component({
    selector: 'my-app',
    template: `
        <div>
            <example [name]="name"></example> <!-- Here you intend to call your child -->
            <input [(ngModel)]="name"/>
        </div>
    `,
})
export class App {
    name: string;
    constructor() {
        this.name = `Angular! v${VERSION.full}`;
    }
}

And Remove that <input [(ngModel)]="name"/> from Example template.

A working stackblitz.

0
votes

@input is only to communicate with outer component not for own template. Instead you can use ngModelChange

import {Component, NgModule, OnInit, OnChanges, SimpleChanges, Input } from '@angular/core'

@Component({
  selector: 'example',
  template: `
   <input [(ngModel)]='name' (ngModelChange)="onChanges()" />
 `,
})

export class Example implements OnInit{
  private _value: string;
  name: string;

  // @Input() name: string; <--- no need

  constructor() {

  }

  ngOnInit() {
    this.name = 'qwe';
  }

  onChanges() {
    console.log(this.name);
  }


}