Sometimes, we want to call another components function in Angular.
In this article, we’ll look at how to call another components function in Angular.
How to call another components function in Angular?
To call another components function in Angular, we can inject the component we want to call the function on as a dependency.
For instance, we write
export class OneComponent implements OnInit, AfterViewInit {
//...
ngOnInit() {}
public testCall() {
alert("I am here..");
}
//...
}
to create the OneComponent component that has the public testCall method.
Then in another component, we inject OneComponent as a dependency and call testCall by writing
import { OneComponent } from "../one.component";
@Component({
providers: [OneComponent],
selector: "app-two",
templateUrl: "...",
})
export class TwoComponent implements OnInit, AfterViewInit {
//...
constructor(private comp: OneComponent) {}
public callMe(): void {
this.comp.testCall();
}
//...
}
We put OneComponent in the providers array.
Then we can inject it as a dependency and the call testCall in TwoComponent.
Conclusion
To call another components function in Angular, we can inject the component we want to call the function on as a dependency.