Skip to content Skip to sidebar Skip to footer

How Do I Call A Function/execute Code Automatically In Angular?

I have code in a function that I need for initialization of other variables. However, this function doesn't get called unless i call it through another tag in html. Is there any wa

Solution 1:

You should have a look at lifecycle hooks that are used in Angular, here is the link to the documents related.

lifecycle hooks

In here you can read about the OnInit() lifecycle hook which is triggered when a component is loaded ( after constructor ) and is an ideal place to look at initialising variables / calling functions.

publicngOnInit(): void {
   this.exampleText = 'Hello Component';
}

just make sure to implement it on your class like so

export classyouClassHereimplementsOnInit {
 
    public exampleText: string;
    
    publicngOnInit(): void {
       //executing logic on component loadthis.exampleText = 'Hello Component';
    }
}

Solution 2:

You can implement OnInit event and do it there. Take a look here OnInit. Check here if you want to now more about Lifecycle Hooks. Alternative option is to use constructor. But that's executed on class initialization.

classMyComponentimplementsOnInit {
  ngOnInit() {
    // ...
  }
}

Solution 3:

You can implement OnInit lifecycle in your class and call your function inside OnInit so that it gets called whenever your component gets mounted.

Post a Comment for "How Do I Call A Function/execute Code Automatically In Angular?"