Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: How to call component method from another component in different modules

Tags:

angular

I am trying to call a method of A_Component owned by A_Module from B_Component owned by B_Module and am getting the following error as soon as I add A_Component as a parameter to the B_Component constructor:

NullInjectorError: No provider for A_Component!

EDIT: The two components are not parent/child. Their modules are imported by app.module

(Code summarized for brevity)

A_Module:

import { A_Component } from '...'

@NgModule({
    imports: [...],
    declarations: [A_Component],
    exports: [A_Component],
})

export class A_Module { }

B_Module:

import { A_Module } from '...'
import { B_Component } from '...'

@NgModule({
    imports: [A_Module],
    declarations: [B_Component]
})

export class B_Module { }

A_Component:

export class A_Component {
    someMethod() {...}
}

B_Component:

import { A_Component } from '...'

export class B_Component {

    constructor(public a_Component: A_Component)) {} //this param causes error

    callSomeMethod() {
        this.a_Component.someMethod();
    }
}

Is this not how to call component methods across modules? Is the only way to do this is with a service?

like image 544
Alex Avatar asked Oct 16 '25 14:10

Alex


1 Answers

Please refer to components interaction official documentation.

You can call only methods of a component declared inside your component using ViewChild.

If you want to make two different component interact with each other - it should be done via common service.

Updated after points from @diopside

like image 137
mykhailo.romaniuk Avatar answered Oct 18 '25 07:10

mykhailo.romaniuk