Access method of one component in other component

1st way : You can use the selector tag of your component in the html file. Create the id of the selector tag and then call the method of another component as shown below:

testComp1.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-testComp1',
  template:'./testComp1.component.html',

})
export class testComp1Component implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  testGroup1(){
    console.log('This is first component.');
  }
}
testComp2.component.html

<div class="container">
<p> This is the html file for test component2.</p>
</div>

Now as you know very well that generally, we can only access the method of the component itself not any other. Then to access simply assign some id to the the component tag as shown below:

<div class="container">
<p> This is the html file for test component2.
<p>
<button class="btn btn-lg btn-outline-primary" (click)="testcomp1.testGroup1()">Click Here</button>
</div>
<app-testComp1 #testcomp1></app-testComp1>

This way is convenient if you don’t have to pass any parameter in the function being called(say testGroup1(content)). Otherwise it will throw error such as ‘attribute content is not defined’.

2nd Way: You can accept this way in both cases like with or without parameter. Say I have to call testGroup1 in testComp2 component.

testComp2.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-testComp2',
  template:'./testComp2.component.html',

})
export class testComp2Component implements OnInit {
  constructor() { }
  ngOnInit() {
  }
  testGroup2(){
   let ob = new testComp2Component();
       ob.testComp1();
    console.log('This is second component.');
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *