0

Below is the explanination provided for OnChanges life cycle event in angular2 documentation.

ngOnChanges - before ngOnInit and when a data-bound input property value changes.

Below is my sample component code

@Component({
   selector:'app-main',
   template:`
      <user-form>Loading....</user-form>
   `,
   directives: [userFormComponent],
   providers: [HTTP_PROVIDERS,UserService]
})

export class AppComponent implements OnInit , OnChanges {

  @Input()
  public prop: string = "hi!";

  ngOnInit() {
     console.log('ngOnInt') ;
  }

  ngOnChanges() {
     console.log('ngOnChanges') ;
  }  

}

And I am refering to this component in my html page like this

<app-main [prop]="test">Loading...</app-main>

Now my question is, even though I am changing databound input property "prop" by assiging value "test", why is that ngOnChanges is not executed. By the way I am new to angular2.

Luca Ritossa
  • 1,118
  • 11
  • 22
refactor
  • 13,954
  • 24
  • 68
  • 103
  • 1
    I believe that only happens on the main component (`AppComponent`). It should work the way it was described on inner components. May due to boostrap process. – Harry Ninh Aug 08 '16 at 05:18
  • That sounds like it. In your example, where should `test` come from? Normally that would be a property on the parent component, but since it's your root app component, there's no component for your index html with a 'test' property to pass to `[prop]`. – Jason Goemaat Aug 08 '16 at 07:45

1 Answers1

1

The problem is that this doesn't apply to main components / root components.

The reason why this is not working is that your index.html in which you place the is not an angular component. Because of this, Angular won't compile this element. And Angular does not read attribute values during runtime, only during compile time, as otherwise, we would get a performance hit.

For this reason, the ngOnChanges hook method doesn't apply.

See this question:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Hi, can you suggest some link where I can find more info on lifecycle hooks, because the information provided in angular2 docs is not in detail. – refactor Aug 08 '16 at 06:08
  • Did you read the following doc: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html? – Thierry Templier Aug 08 '16 at 06:11