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';
}
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.
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.
The short answer is to use ViewChild to call the function on component B.
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.
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*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With