Implemented ngOnInit() hook by using instance bound method and it stoped working....
Simplified example:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>'
})
export class AppComponent {
name = 'Angular';
ngOnInit = () => {
this.name = 'World';
}
}
expected result => "Hello World" real result => "Hello Angular"
Is it described somewhere that exactly that methods are disallowed to be used exactly for hooks? Or what is the problem w/ using them as such?
Live example: https://plnkr.co/edit/aZ1CYkDn06KUENmDW3a3?p=preview
IMPORTANT: Question is not how to fix. I know that i could change to ngOnInit() {}. The question is - why instance bound method does not work as a hook
FOLLOW UP Created an issue in the Angular repo - to improve behavior / docs / error notifications: https://github.com/angular/angular/issues/16478 guess there will be more clear answer. Will post it here after it will be clear / confirmed that behavior is by design checking the class prototypes only.
It should be
ngOnInit() {
this.name = 'World';
}
Think of it like you are overriding the default cycle
Fixed plunker: https://plnkr.co/edit/DGkNulwYs4WpYULhl9gD?p=preview
Note:
Implementing the life-cycle hooks are optional as it says in the documentation. Because javascript doesn't have interfaces
Source: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#interface-optional
Edit:
What you are doing is just creating a function inside your component which is named ngOnInit if you want to execute it you have to do it somewhere inside your component. The best place to do it seems like the constructor:
constructor(){
this.ngOnInit();
}
Fixed plunker: https://plnkr.co/edit/NAHX5vfoMXtN95Y0oyOR?p=preview
Edit2:
Here's the proof of the prototype:
With the way you do it, the function will not be a part of the prototype chain of the component base class (line 17):

But this way Angular will see it as a part of the prototype chain (line 15):

Add the implements and change the ngOnInit like echonax say:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>'
})
export class AppComponent implements OnInit {
name = 'Angular';
ngOnInit() {
this.name = 'World';
}
}
Explicitly declare that the component implements OnInit and fix the function implementation syntax:
export class AppComponent implements OnInit {
public ngOnInit(): void {
this.name = 'World';
}
}