My tutor told me that, "In angular we can use function defined in any service by just importing that service but we can't import a component in any other component. To use function defined in any other component we need to use @ViewChild(ComponentName)."
But when I tried to call function of a component in other component without using @viewChild, I was successful and there was not any error occurred.
Please refer the below example to understand the scenario:
CASE1: Calling function of a component in other component without using @ViewChild
Suppose we have a component "testcomponent" and in that component we have a "hello" function as below:
testcomponent.component.ts
import { Component, OnInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-testcomponent',
templateUrl: './testcomponent.component.html',
styleUrls: ['./testcomponent.component.css']
})
export class TestcomponentComponent implements {
constructor(){}
hello(){
console.log("Hello ABC");
}
}
To use the "hello" function of "testcomponent" component in "app" component, I tried the following:
app.component.ts
import { Component} from '@angular/core';
import { TestcomponentComponent } from './testcomponent/testcomponent.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
constructor(private testcomponent : TestcomponentComponent ){};
ngAfterViewInit(){
this.testComponent.hello();
}
}
Here "Hello ABC" get printed in the console and there was not any error occurred.
CASE2: Calling function of a component in other component with using @ViewChild
Now consider the case when I used @ViewChild in "app.component.ts" file to call "hello()" function of "testcomponent" component:
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit{
@ViewChild(TestcomponentComponent,{static:false}) viewChildOnComponentSelector : TestcomponentComponent;
ngAfterViewInit(){
this.viewChildOnComponentSelector.hello();
}
}
Since in CASE1 I was able to call "hello()" method of "testcomponent" in "app" component, then why we need @ViewChild as in CASE2?
Also please explain me, if we can call function of any component in any other component by just importing that component (as in CASE1) , then what is the difference in calling a function of a Component or a Service?