1

What is the difference between initialzing a component's property directly in the component class VS initializing it in the ngOninit method ?

Example :

@Component({})
export class AppComponent {
    property: string = 'some initial value'
}

   **VS**

@Component({})
export class AppComponent implements OnInit{
    property: string;

    ngOninit(): void {
        this.property = 'some initial value';
    }
}
Mer Mer
  • 83
  • 11
  • 1
    You may find [this answer](https://stackoverflow.com/questions/66603888/where-to-initialise-a-formgroup-in-reactive-forms/66607035#66607035) helpful. – BizzyBob Feb 11 '23 at 13:00

2 Answers2

2

If anything is statically initialized, there is basically no difference. If your parameters depend on @Input parameters on the other hand, these will not be available in the constructor, but will be set before the ngOnInit hook is called. So the common pattern is to treat the ngOnInit method as a constructor block.

Loop
  • 480
  • 2
  • 9
1

Have a read about Angular Lifecycle Hooks.

Here you had a simple example where you are just setting the property a static value but for a case where property's value depends on an API service then you should use life-cycle hooks for playing with the values

A simple example of setting the property with a value which you get from a API service which will get data from a REST API

@Component({})
export class AppComponent implements OnInit{
    property: string;
    constructor(private apiService:ApiService){}
    ngOninit(): void {
        this.apiService.getAPIData.subscribe((data)=>{
          this.property = data;
        });
    }
}

Here is another comparison which explains @Input availability from ngOninit

Kaneki21
  • 1,323
  • 2
  • 4
  • 22