Using methods from one component in another with NgModules

There are two modules in my project, a root module and a shared module. Below is the code for the shared module:

import { NgModule } from '@angular/core';
import { SomeComponent } from "./somecomponent";
@NgModule({
    declarations: [SomeComponent],
    exports: [SomeComponent]
})
export class SomeModule {}

In my Root module, I import the SomeModule like this:

import { NgModule }       from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { SomeModule } from somemodule/somemodule';

@NgModule({
    declarations: [AppComponent],
    imports:      [BrowserModule, SomeModule],
    bootstrap:    [AppComponent], 
})
export class AppModule {}

Everything works perfectly until now. Now, I want to access a method that belongs to SomeComponent inside my app.component. However, the issue is that the shared module does not directly expose SomeComponent.

How can I call methods from SomeComponent in the AppComponent class? What if the method is static?

EDIT : To clarify further, SomeComponent is a directive that I am able to use in the template of

AppComponent</code without any problems. However, it also contains a static method that I need to call within the <code>AppComponent
class. Since I have imported it in the Root module, it should be available inside the AppComponent. I would like something similar to this in the AppComponent:

import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    template: `<some-component (someEvent)="handle($event)"></some-component>`
})
export class AppComponent {

  _constructor(){}

  handle(event){

   SomeComponent.someStaticMethod();

  }
}

Answer №1

UPDATE: To achieve your goal, Angular2 offers a feature called ViewChild.

import { Component, ViewChild } from '@angular/core';
import { SomeComponent } from './some.component';

@Component({
    selector: 'my-app',
    template: `<some-component (someEvent)="handle($event)"></some-component>`
})
export class AppComponent {
    @ViewChild(SomeComponent) private someComponent:SomeComponent;

    constructor () {}

    handle(event) {

        this.someComponent.someStaticMethod();
    }
}

I have included a Plunk for reference: https://plnkr.co/edit/8aGi4GNWUAKdf01ZPplB?p=preview

RESPONSE INITIATED

If you are referring to components in the context of classes in general, there are certain ways to interact with child components in Angular2. One approach is to utilize a #spy to invoke methods of the child component:

<parent-component>
    <child-component #child></child-component>        
    <button (click)="child.someMethod()">Call method of child</button>
</parent-component>

In cases where you wish to access public methods of a class across different modules or components, consider using the @Injectable() decorator and passing the class (or service) instance to the constructor of each requiring component. Alternatively, you can create a new instance of the class (let a = new MyClass();) and directly call its public method (a.somePublicMethod();).

Note that beyond classes and components, it's also possible to export a plain function in ES6:

export function myFunction(a: any, b: any) {
  // ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When working with Typescript, it is important to correctly identify elements as checkboxes in order to avoid any red underlines when referencing

When trying to check the input type of an element, such as a checkbox in TypeScript, I encounter the issue of the 'element.checked' property being underlined in red. The code snippet below shows how I attempt to address this: element: HTMLElemen ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

Angular 6 CSS spacing dilemmas

We recently made the switch from Angular 5 to Angular 6 and noticed that there is no spacing between the buttons/icons, etc. We are looking to bring back the spaces between the buttons and icons. I have recreated the issue below. As you can see in the Ang ...

There seems to be a problem as I am unable to match any routes. Does anyone have any suggestions on how I can resolve this issue?

I am currently developing an Angular recipe application. I have a feature where users can click on the "Full Recipe" button in the saved recipes page to view detailed recipe information. The functionality works perfectly in the recipe item component, but w ...

Asynchronous and nested onSnapshot function in Firestore with await and async functionality

I'm facing an issue with the onSnapshot method. It seems to not await for the second onsnapshot call, resulting in an incorrect returned value. The users fetched in the second onsnapshot call are displayed later in the console log after the value has ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

Exploring the attributes of a record through a combination of string template types

I'm utilizing a string template type to denote ids with a significant prefix, such as dta-t-${string} where dta-t- encodes certain details about the entity. I have various record types that are indexed by unions of string templates: type ActivityTempl ...

Establish a permanent code folding feature in the Monaco editor for enhanced text organization

I need help implementing persistent code folding on the Monaco editor. Specifically, I am unsure about: how to extract the view state when it changes; storing it in localstorage; and then restoring it when Monaco is loaded. Although I am aware of saveVie ...

There was an error encountered: Uncaught TypeError - Unable to access the 'append' property of null in a Typescript script

I encountered the following error: Uncaught TypeError: Cannot read property 'append' of null in typescript export class UserForm { constructor(public parent: Element) {} template(): string { return ` <div> < ...

Backend not receiving the request

While all tests pass successfully in Postman, I'm encountering an issue where requests are not reaching the backend when testing from the front-end. import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common ...

Leveraging Angular 2 Service with the Power of RxJS BehaviorSubject or EventEmitter

Being new to Angular 2 and RXJS, I find myself faced with a challenge involving a custom header component that has 2 triggers (buttons) meant to activate 2 distinct navigation directives in different areas of the application. To address this issue, I have ...

Efficient Ways to Utilize Global CSS in an Angular Project Without CLI

I am utilizing ASP.NET MVC as the server and Angular as the client application. Instead of a static index.html file, I have index.cshtml. The styles I am using are global styles rather than component-scoped. My query revolves around working with a bunch ...

What are some effective strategies for creating customizable and dynamic filtering and sorting features in Angular (^11) that can be reused across different components?

I am looking to integrate custom ordering and filtering capabilities into my application in a way that is easily reusable across various components. These functions will be essential for enabling users to sort list/table contents and filter arrays within t ...

I am encountering an issue with retrieving JSON data within an ngrx effect

I've been struggling for the past two days trying to display local json data (posts) in my view (PostsComponent). I keep encountering this error message in the console: ERROR Error: Cannot find a differ supporting object '[object Object]' of ...

Design an array specifically for runtime using a union type

Imagine I have the following union type: type Browser = 'Chrome' | 'Firefox' I am looking to convert this into an array: const browsers = /* code to change Browser type into ['Chrome', 'Firefox'] The goal is to u ...

The error message "core.js:10101 NG0303: Unable to link to 'matCellDefOf' because it is not a recognized property of 'td'" was displayed on the console

While utilizing Mat table from Angular Material, an error appears in the console as shown in this image: core.js:10101 NG0303: Can't bind to 'matCellDefOf' since it isn't a known property of 'td'. View image description here ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Is there a way to locate all items that satisfy a specific criterion within JSON Data?

Utilizing data from an API-Call, I have established a many-to-many relationship - illustrated with the examples of people and movies. Multiple individuals can watch one movie, and one person can view several movies. In the Angular Frontend, when a person ...

The functionality of the dynamic drag and drop form builder is not functioning as expected in Angular 12

I am currently developing a dynamic form builder using Angular version 12. To achieve this, I decided to utilize the Angular-Formio package. After installing the package and following the steps outlined in the documentation, I encountered an issue. The i ...