When it comes to assigning values in your Angular class, there are a few different approaches you can take depending on how you have set up your component.
If your class implements OnInit
, it is recommended to do the assignment in the ngOnInit()
method like this:
export class SampleComponent implements OnInit{
data: any;
ngOnInit(){
this.data = 'example';
}
}
Alternatively, if you are not using OnInit
, you can directly assign the value in the constructor as suggested by others:
export class SampleComponent{
data: any;
constructor(){
this.data = 'example';
}
}
Lastly, you can also assign a value at the time of variable declaration like this:
export class SampleComponent implements OnInit{
data: any = 'example';
ngOnInit(){
}
}