invoke a method from an existing component within a different component

section 1

import { Component } from '@angular/core';
@Component({
    selector: 'app-section1',
    template:
    `
    <button (click)="submit()"></button>
    `
})
export class Section {

    constructor() { 
    }
    someFunction(): void {
    }
}

section 2

import { Component } from '@angular/core';
    @Component({
        selector: 'app-section2',
        template:
        `
        <p>text</p>
        `
    })
    export class Section2 {

        constructor() { 
        }
    }

i want to call the section 1 someFunction() from section 2

section 1 and section 2 haven't any direct relation.

is there a way to access the instance of section 1 in section 2

in JavaScript, something like this

MyClass myClass = applicationContext.getBean("myClass");

is there any possible way like this in angular without using BehaviorSubject or EventEmitter?

Answer №1

One way to pass data from component A to component B is through the parent template that both components are a part of. There isn't a central repository where you can access all component instances. If direct template connections aren't desired, consider using a shared service instead.

Example in app.component.html:

<component-a #refA></component-a>
<component-b [refA]="refA"></component-b>

@Component({...})
export class ComponentA {
    public someMethod() { }
}

@Component({...})
export class ComponentB implement OnInit {
    @Input() refA: ComponentA;

    public ngOnInit() {
        if(this.refA) {
            this.refA.someMethod();
        }
    }
}

However, this approach has its drawbacks:

  • You may encounter an this expression has changed after being checked error.
  • If you modify the state of ComponentA externally, you'll need to mark its view as dirty.

It's generally not recommended to directly alter another component's internal state from outside its view as it goes against best practices. Using a shared service along with observables is a more preferred solution.

Answer №2

One approach could be to set up a service that can access and interact with another component by passing in its reference point:

import { Component } from '@angular/core';
import { CustomComponentService } from 'path/to/customcomponentservice';
@Component({
    selector: 'app-custom-component',
    template:
    `
    <p>content here</p>
    `
})
export class CustomComponent {
    ViewChild('targetComponent') targetComponent: Component;

    constructor(private customComponentService: CustomComponentService) { 
        this.customComponentService.connectToComponent(this.targetComponent);
    }
}

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

Using *ngFor and [(ngModel)] simultaneously in Angular2 and Ionic2

Is there a way to combine *ngFor and [(ngModel)] in order to dynamically update data in a list? Here's a straightforward code snippet for reference: <ion-item *ngFor="let item of items" [(ngModel)]="item.title"> {{item.title}} </ion-item&g ...

Waiting for an observable to load the page in Ionic 2

When loading a page that calls an API to fetch objects for display, I encounter an issue where the page finishes loading before any data is received, resulting in an empty display. constructor(public navCtrl: NavController, public userData: UserData, publ ...

Upgrade from Angular 4 to Angular 5 via the Visual Studio template is causing some challenges

I am in the process of upgrading my Angular project from version 4 to version 5, which is included in the template provided by Visual Studio 2017 (File -> New -> Project -> ASP.NET Core Web Application -> Angular). However, all the angular pac ...

The specific type 'Observable<{}[]>' cannot be matched with type 'BrandElement[]'. The property 'includes' is not found in the type 'Observable<{}[]>'

I am currently utilizing Firebase as my database solution and attempting to fetch data to display in an Angular 6 table. Below is the interface and component class for this scenario: export interface BrandElement { name: string; image: string ...

I am unable to modify values using ngModel

I am struggling to update the value in my service.year.ts file but it seems impossible... <select name="selectedyear" [disabled]="disabledPeriod" [(ngModel)]="selectedyear" (ngModelChange)="onChangeYear()"> <option [ngValue]="selectedyear" ...

Ways to exchange data between different "input" sources

Is there a way to automatically transfer data entered in the first "input" field (full_name) to the second one (short_name)? <form [formGroup]="form"> <div class="row"> <div class="input-field col s12 m6"> <input formContro ...

Updating an element within a for loop using Angular TypeScript

I'm trying to figure out how to update the value of an HTML DOM element that is bound from a TypeScript file in each iteration of a for loop, rather than at the end of the loop. I want to see all values as the loop is running. For example, imagine I ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Utilizing Async/Await to Streamline Google Maps Elevation Requests

I'm struggling to run this in a sequential manner. I've experimented with various methods like using Promise.all and getting stuck in callback hell, but what I really need is to obtain elevations for each point that has a valid altitude value (no ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

Button in Angular gets stuck when a touchscreen is long pressed

In my Angular2 application, I am facing an issue with a button when running on a Windows 10 touchscreen PC in Chrome. Normally, the button works fine and executes the click function. However, if the button is held for 1-2 seconds, it gets stuck and fails t ...

Typescript: Understanding the question mark usage on arrays

In this example, I have the basic structure of my code: let myArray: (Array<any> | null); if (cnd) { myArray = []; myArray?.push(elt); // Curious about this line myArray[0].key = value; // Questioning this line } else { myArray = null; } Wh ...

Is it advisable to move operations outside of the useEffect hook?

Is it advisable to move code outside of the useEffect function in React? function BuyTicket(props: any) { useEffect(() => { //.. }, [eventId, props.history]); // IS IT RECOMMENDED TO PUT CODE HERE? const userNameL ...

What is the proper way to define a tuple type with a specific size N for the vector class in C++?

I am seeking to create a tuple type with a fixed size N, allowing for functionality such as: let tuple: Tuple<string, 2> = ["a","b"] In this scenario, "number" represents the type T, and "2" denotes the size N. Subsequently, I ai ...

Troubleshooting problem with Webpack and TypeScript (ts-loader)

Seeking help to configure SolidJS with Webpack and ts-loader. Encountering an issue with return functions. What specific settings are needed in the loader to resolve this problem? import { render } from "solid-js/web"; const App = () => { ...

Encountering the error message 'Object is of type unknown' when implementing the createAsyncThunk function post utilization of Typescript and Redux Toolkit

Currently, I am utilizing Typescript in my React application where Redux Toolkit is being used for state management. The data is being fetched from an Express Api and everything operates smoothly if Redux is implemented without Typescript. However, when in ...

I am facing conflicts between vue-tsc and volar due to version discrepancies. How can I resolve this problem?

My vsCode is alerting me about an issue: ❗ The Vue Language Features (Volar) plugin is using version 1.0.9, while the workspace has vue-tsc version 0.39.5. This discrepancy may result in different type checking behavior. vue-tsc: /home/tomas/Desktop/tes ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Error: Found an unexpected character '&')' during parsing

When using the ng build --configuration=production command to build a project, an error may sometimes occur for certain systems. This error might be resolved by clearing the cache, but it could persist in some cases. I opted for Angular version 12. https ...

Is there a way to display an array of data in separate mat-form-field components?

I am dealing with an array that stores 4 data points: [onHour, onMinute, offHour, offMinute]. I also have 4 elements that are not in an array and need to be repeated. <div class="on"> <mat-form-field appeara ...