Sharing data between two Angular components without using HTML

In my file structure, I have: 1. a topbar folder - with html(1) and ts(1) for the topbar 2. a page folder - containing html(2) and ts(2) for the page

But now, there's a BUTTON in html(1)

<button (click)="refresh()" class="navbar-btn btn btn-success btn-md refresh">
    <span class="glyphicon glyphicon-refresh"></span> Refresh
</button>

And there's a function in ts(1)

refresh()
{
console.log("this is topbar html and ts");
}

Next, there's a function in html(2)

I don't need to do anything here!

Also, there's a function in ts(2)

refreshEvent(){
console.log("i want use this function in html(1) BUT HOW??")
}

So, when I click the button, it should call refreshEvent()

Answer №1

Utilizing the Subject feature from rxjs is a viable option,

import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MyService {
    private subject = new Subject<any>();
    refresh() {
        this.subject.next();
    }
    onRefresh(): Observable<any> {
        return this.subject.asObservable();
    }
}

In Component B:

  constractor(private myService: MyService){}
  this.$subscription = this.myService.onRefresh().subscribe(() => this.refreshEvent() );
  ngOnDestroy() {
        this.$subscription .unsubscribe();
    }

For Component A:

constractor(private myService: MyService){}

refresh()
{
  //console.log("this is topbar html and ts");
 this.myService.refresh();
}

If there exists a child-parent relationship, output events can be employed, refer to the documentation for further details: https://angular.io/guide/component-interaction

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

In the function ngOnChange, the SimpleChange currentValue is supposed to be defined, but for some reason, the

Within the TypeScript code, a name variable is assigned input from another component. @Input() name : any ; In the ngOnChange function, I retrieve and print the SimpleChange object in the following manner. ngOnChanges(changes: SimpleChange){ console.l ...

Having trouble installing the generator-angular2

While attempting to install generator-angular2, an error message is displayed: npm WARN ENOENT ENOENT: no such file or directory, open '/usr/local/lib/node_modules/generator-angular2/package.json' npm WARN ENOENT ENOENT: no such file or direc ...

When the observable is subscribed to, the data is not immediately available

I am encountering an issue with syncing data from an observable in a service with a component that consumes the data. The data service makes a call to an api service upon creation to gather a list of devices from a server. It seems like this process is fun ...

Error: Unable to access the 'invalid' property of a null object - Issue with Angular Reactive Forms

In my Angular application, I have implemented a reactive form to allow users to input IP address ranges. This form utilizes a FormBuilder to create a FormArray with two text input form controls. The code for setting up the form and managing its elements is ...

Exploring a specified set of numbers with PrimeNG's input number spinner for looping

Is there a way to iterate through a series of numbers, such as from 0 to 10, using the PrimeNG input number spinner? ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Best practices for utilizing React.Provider in Typescript to manage and refresh user context

I'm currently trying to wrap my head around how Typescript is structured. However, my Typescript React web app is failing to build due to the following error: Type '({ user: { id: any; }; } | Dispatch<SetStateAction<{ user: { id: any; }; }& ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

Angular2 CLI express server.ts encountered an unexpected import token

Starting an Angular2 project and setting up the server with express and Angular CLI version 1.0.0-beta.25.5 has been challenging for me. The file structure looks something like this: project root |-server |-server.ts |-src |-app When attempting to r ...

Tips for efficiently loading data in a sequence using rxjs: within each sequence, there could be multiple calls made

const dates = [{start:'03/06/2020', end: '03/09/2020'}, {start:'03/12/2020', end: '03/03/2021'}, ...] const fetchData = service.get(page = 1, dates[0]) and service.get(page = 2, dates[0]) retrieves the necessary d ...

Obtaining the current date and time of the user's browser within a server-rendered file

I need to capture the browser/local date and time in a PDF file. The challenge I'm facing is that the PDF file rendering occurs on the server, which means I can't use JavaScript to achieve this as the rendering process is server side. Can anyone ...

Connect store variables to components using Angular's ngrx

I am attempting to link the location variable in my component to another variable in the store using a selector with ngrx v13 in Angular. However, when I include the variable with the property in the HTML, I encounter an error: Error message: Property &ap ...

Dynamically apply classes in Angular using ngClass

Help needed with setting a class dynamically. Any guidance is appreciated. Below is the class in my SCSS file: .form-validation.invalid { border: 2px solid red } In my ts file, there's a variable named isEmailValid. When this variable is set to ...

Tips for predefining an array of React Elements in TypeScript

import { Button, ButtonGroup } from '@material-ui/core'; let buttons: React.Component[] = []; leads to an error message stating: Type 'Element' is missing the following properties from type 'Component<{}, {}, any>': con ...

The KeyValuePair<string, Date> type in Typescript cannot be assigned to the KeyValuePair<number, string> type

I encountered the following issue: An error occurred stating that Type 'KeyValuePair<string, Date>' is not assignable to type 'KeyValuePair<number, string>'. Also, it mentioned that Type 'string' is not assignab ...

What is the process for converting BitmapData from Flash into HTML canvas?

Currently facing a significant challenge as I transition from using Flash to JS. The issue lies in handling SOAP returned data, specifically when dealing with images stored as strings that need to be converted into BitmapData for use in Flash. Despite tryi ...

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...

Using ReactJS to activate child components from a parent component

I am working on a parent component that functions as a Form in my project. export default class Parent extends Component{ submitInput(event){ ...calling Children components } render(){ ...

How about: "Are you utilizing the recoil selector for sorting through component

After diving into numerous examples, documentation, and videos about using selectors with recoil, I still can't seem to wrap my head around it. Maybe it's just one of those off days because it shouldn't be this difficult. Here's where ...