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

Tips for setting up a mdl-dialog using a declarative approach

I want to incorporate a mdl-dialog into my component following the example provided here: However, when I try to do so, the compiler throws an error stating: Can't bind to 'mdl-dialog-config' since it isn't a known property of ' ...

Error message: The provider is not being recognized by react-redux while using NextJS with RTK and

Struggling to integrate Redux RTK into my Next JS 13.4 app has been quite the challenge. No matter how many tutorials I follow, I keep encountering the same error in my provider.ts file. 'use client' import { store } from './store'; imp ...

The functionality of two-way data binding seems to be failing in Angular 2

I encountered an issue in my Angular 2 application where I attempted to bind view data using ngModel, but it did not function as expected. event.component.html <div class="form-group"> <label for="comment">About Us:</label> ...

Automatic Formatting of Typescript in SublimeText

Utilizing Microsoft's Typescript Sublime Plugin, I am able to format a file using the shortcut ^T ^F as outlined in the plugin's feature list. Is there a method to automatically execute this command when saving a file? Similar to the functionali ...

Verify whether a web application is equipped with React, Angular, or Vue

Is there an easy way to identify the client-side libraries used by an application if they are minified or compressed? While examining all the JavaScript sent from the server to the client, it can be challenging to determine if one of the top three popular ...

The for loop finishes execution before the Observable in Angular emits its values

I am currently using a function called syncOnRoute() that returns a Promise. This function is responsible for synchronizing my data to the API multiple times based on the length of the data, and it returns a string message each time. However, I am facing a ...

Anticipating the completion of post requests

I am currently working on implementing a file upload feature in Angular. I have tackled the issue of file size restrictions by creating an API endpoint that can receive file chunks. Once all the chunks are received, another endpoint needs to be triggered ...

Switching from lite-server to my own express server.js file for Angular 2: Step-by-step guide

Recently, I decided to take on the challenge of migrating my existing Angular 1.x project to Angular 2. While I wanted to switch to TypeScript and Angular 2 for the client side, I preferred to keep my existing server code intact. However, I encountered an ...

Best practice for importing ts files from an npm package

When faced with the need to divide a ts project into multiple repositories/packages for creating microservices, the challenge arises in combining these packages efficiently. Some packages are required in one microservice, others in another, and some in all ...

Tips on enabling click function in an ionic infowindow

After creating a div in my HTML file and referencing it in my TS file using document.getElementByID, I utilized its inner HTML as the content for an infowindow. However, despite my efforts, I am unable to get clicks working. Adding event listeners to any e ...

npm error - The module './selenium-webdriver/lib/input' cannot be located

After updating my Angular project from version 5 to 7, I encountered numerous vulnerabilities. To address this, I followed the suggested commands in "npm audit" which successfully fixed all the vulnerabilities. However, when attempting to run: ng serve ...

Ways to remove the default classes added by ngbootstrap

My current challenge involves utilizing ngbootstrap for popovers, yet desiring to override its default styling. Specifically, I have a form that should function as a popover triggered by a button click, and it needs to maintain its own distinct styles. Up ...

The element 'loginToken' is not found within the type '{ loginToken: string; } | { error: Error; } | { username: string; password: string; }'

I'm currently working on creating a reducer using Typescript and Redux, but I keep running into this error: Property 'loginToken' is not recognized in type '{ loginToken: string; } | { error: Error; } | { username: string; password: str ...

Getting the Final Character from a TypeScript String Constant

Can we extract the final character from a string without using the entire alphabet as an enum? Right now, I'm focusing on numeric digits. I'm somewhat puzzled about why my current approach isn't yielding the correct results. type Digit = &a ...

Challenges of Vue 3 Typescript ComputedRef

I've run into some challenges with Typescript and Vue3. It seems like I might be using Typescript incorrectly in this case. I set up a store using Vue's Composition API. import {computed, reactive} from "vue"; const state = reactive({ ...

Is there a way to make divs expand on top of existing content when hovering over them, in order to avoid needing to scroll through overflow content? I am currently working with

I am working with 9 boxes contained within divs, each box includes data that exceeds the size of the box itself (represented by Some Text repeated for demonstration purposes). I am seeking a solution where hovering over any box will cause it to enlarge and ...

Running "ng lint --fix" does not automatically correct the issues in my files, but it does effectively pinpoint all the errors that need to be addressed

I am currently working on resolving lint issues present in files that are automatically generated through openapi-generator. Let's take a look at one of the files that needs fixing: To address these errors, I have been using the following command: ...

Using TypeScript to narrow down types within mapped types

Can you create a mapped type based on the property type? For example, if I want to map all properties with type String to Foo and all other types to Bar. Can this be done like this: type MappedType<T> = { [P in keyof T]: T[P] === String ? Foo : B ...

Steps for sending data from Angular2 or Angular4 to a Node.js server and saving it in a MySQL database:1. In your

I've scoured the depths of the internet on Google but have come up empty-handed in finding a reliable working example. Any assistance would be greatly appreciated as I am relatively new to Angular2 (angular4). My goal is to have my angular2 applicati ...

What steps should I take to resolve the No Session error during the authentication process in a Laravel 9/Angular 13 SPA?

My Angular 13 SPA is successfully authenticating to Laravel 9 (Sanctum), as I am able to obtain the CSRF cookie and complete the authentication step. However, when I try to access other protected API endpoints, I am encountering a 'No Session' er ...