Angular Call Component Method from Another Component Example

By Hardik Savani October 20, 2023 Category : Angular

In this post, we will learn how to call another component function in angular. I’m going to show you about how to call one component function from another in angular. We will look at example of how to call another component function in angular. let’s discuss about call method from one component to another component angular 8. Let's get started with angular call component method from another component.

I will give you two way to use one component function to another component in angular 6, angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 application.

Let's see both example that will help you.

Example 1:

src/app/app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

import { CompOneComponent } from './compOne.component';

import { CompTwoComponent } from './compTwo.component';

@NgModule({

imports: [ BrowserModule, FormsModule ],

declarations: [ AppComponent, CompOneComponent, CompTwoComponent ],

bootstrap: [ AppComponent ]

})

export class AppModule { }

src/app/compOne.component.ts

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

@Component({

selector: 'app-comp-one',

template: `<div>

<p>Call Component One</p>

</div>`,

})

export class CompOneComponent implements OnInit {

constructor() { }

ngOnInit() {

}

myFunctionOne(){

console.log('Call Function One from Component One');

}

}

src/app/compTwo.component.ts

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

@Component({

selector: 'app-comp-two',

template: `<div>

<p>Call Component Two</p>

<button (click)="one.myFunctionOne()" >Call Component One Method</button>

<app-comp-one #one></app-comp-one>

</div>`,

})

export class CompTwoComponent implements OnInit {

constructor() { }

ngOnInit() {

}

}

Output:

Call Function One from Component One

Call Function One from Component One

Call Function One from Component One

Call Function One from Component One

Example 2:

src/app/compTwo.component.ts

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

import { CompOneComponent } from './compOne.component';

@Component({

selector: 'app-comp-two',

template: `<div>

<p>Call Component Two</p>

</div>`,

})

export class CompTwoComponent implements OnInit {

constructor() { }

ngOnInit() {

let myCompOneObj = new CompOneComponent();

myCompOneObj.myFunctionOne();

}

}

Output:

Call Function One from Component One

I hope it can help you....

Shares