Search code examples
angularconstructorngoninit

call initialize method in ngOnInit or constructor


Im very new to Angular 4,

Can you tell me what is the different between call a method like initializeMyObj() in constructor than ngOnInit in ts file?

Thank you


Solution

  • The major difference is that constructor is typescript construct whereas ngOnInit is life cycle hook of component and directive.

    Constructor is used to initialize the component. At this time, @Input bound properties are not initialized.

    On the other hand ngOnInit is called once after constructor and ngOnChange. At this time, the component is initialized and properties are bound.

    @Component({
    ...
    })
    export class MyComp{
        @Input() someprop;
        constructor(){
            console.log(someprop); //undefined
        }
        ngOnInit(){
            console.log(someprop); 
        }
    }