Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a function on init in app.component.ts

This might be a really stupid question, but I've noticed that the <app-root> in angular does not implement OnInit like all other components. Say I wanted to put a simple console.log('Hello World') in for a example and I wanted that to show every time the app-root was loaded (stupid I know but simple enough for this example), where in the code structure would I do this and does it need a special function name (eg. ngOnInit())? Or is the whole point of angular for this to be nothing more than just a wrapper that initialises other components.

Here's the code in it basic format as the Angular CLI installs it:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

}
like image 569
Web Develop Wolf Avatar asked Aug 20 '18 15:08

Web Develop Wolf


People also ask

How do you call a function in app component?

We can click the “Call Function” button. It will call the function in the first component. Now we can click the second component link and click the “Call First Component Function” button. It will execute the function from the first component and will show the same message box as given below.

What is ngOnInit () How do you define it?

ngOnInit()link A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.

How do you call ngOnInit of another component?

The short answer is to use ViewChild to call the function on component B.

How do you use ngOnInit?

Use ngOnInit() whenever you want to execute code when the component is FIRST initialized. Remember that ngOnInit() only fires once after data-bound properties are set. This means ngOnInit() will execute if you refresh your browser or first initialize a component but not when other events occur.


1 Answers

Yes you can add it just like the other components:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  ngOnInit() {
    console.log();
  }

}

Also, it's not that you shouldn't do it. Like anything else, there should be a reason. It just depends on what you are trying to do. That's what more accurately would determine whether or not what you are trying to do is correct/incorrect or good practice/bad practice*

like image 181
David Anthony Acosta Avatar answered Oct 14 '22 00:10

David Anthony Acosta