HDTuto.com

Call Method from One Component to Another Component in Angular



Hi

Are you looking for example of how to call another component function in angular. step by step explain call method from one component to another component angular 8. This tutorial will give you simple example of angular call component method from another component. you'll learn how to call another component function in angular.

I will give you two way to use one component function to another component in angular 6, angular 7, angular 8 and angular 9 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....




April 26, 2020 | Category : Angular



Blog Search