Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option using output(). Typically, this involves creating an EventEmitter and having interested components subscribe to it. Is there a simpler way?

It would be great to have a solution that doesn't require subscriptions and EventEmitters.

Here's an example of what I'm referring to:

export class PriceQuoterComponent {
  @Output() lastPrice = new EventEmitter<PriceQuote>();

  priceQuote: PriceQuote;

  constructor() {
    interval(2000)
      .subscribe(data => {
        this.priceQuote = {
          stockSymbol: 'IBM',
          lastPrice: 100 * Math.random()
        };

        this.lastPrice.emit(this.priceQuote);})


}

Answer №1

In my opinion, I would not suggest this approach; however, an alternative method is to pass a function as an input and invoke it whenever there is a change:

export class StockWatcherComponent {
  @Input() newPrice: Function<Number>;

  priceUpdate: PriceUpdate;

  constructor() {
    setInterval(2000)
      .subscribe(data => {
        this.priceUpdate = {
          stockSymbol: 'AAPL',
          currentPrice: 150 * Math.random()
        };

        if (this.newPrice) {
          this.newPrice(this.priceUpdate);
       }
   })
}

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

Angular drag and drop feature for interacting with intersecting elements like rows and columns within a table

I am currently working on implementing two intersecting drag and drop functionalities using cdkDragDrop. Although I generally try to avoid using tables, I have created one in this case for the sake of easier explanation. Here is the link to StackBlitz: ht ...

Implementing ngClass with a dynamic ID in the URL condition

I am attempting to create an ngClass condition that adds an active class to a list element. Specifically, I want it to work for both the URLs '/companies' and '/company/:id'. The issue I am facing is that the current setup does not fun ...

Tips for Logging HTTP Communication Errors in Angular

When making an HTTP put call to update a record in my .Net MVC application, I have noticed that the controller's put logic is not being triggered as expected compared to other types of HTTP requests. I want to implement error handling by using the Ha ...

A guide to mastering Nested Table creation in Angular

I'm in the process of creating a dynamic table using an array of data let data = [{ "criterialimitId": "3", "criteriaName": "Test", "criteriaId": "1", "criteria": "Max Wager", "type": "DAILY", "oprLimit": "2.5", "status": "1", "acti ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

The attribute 'forEach' is not recognized on the data type 'string | string[]'

I'm experiencing an issue with the following code snippet: @Where( ['owner', 'Manager', 'Email', 'productEmail', 'Region'], (keys: string[], values: unknown) => { const query = {}; ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

Having trouble figuring out how to display a tooltip using the show() method in @teamhive/ngx-tooltip?

I am looking for a way to toggle this tooltip on and off as I navigate with my mouse, especially because it is attached to nested elements. Although I can detect cursor movement for other purposes, I need a solution for controlling the tooltip display. Ac ...

Tips for validating an object with unspecified properties in RunTypes (lowercase object type in TypeScript)

Can someone please confirm if the following code is correct for validating an object: export const ExternalLinks = Record({}) I'm specifically asking in relation to the repository. ...

What is the importance of using ChangeDetectorRef.detectChanges() in Angular when integrating with Stripe?

Currently learning about integrating stripe elements with Angular and I'm intrigued by the use of the onChange method that calls detectChanges() at the end. The onChange function acts as an event listener for the stripe card, checking for errors upon ...

Issue with handsontable numbro library occurs exclusively in the production build

Encountering an error while attempting to add a row to my handsontable instance: core.js.pre-build-optimizer.js:15724 ERROR RangeError: toFixed() digits argument must be between 0 and 100 at Number.toFixed () at h (numbro.min.js.pre-build-op ...

ngx-emoji mart - The error message "Type 'string' is not assignable" is being displayed

While working on a project involving the @ctrl/ngx-emoji-mart package, I encountered a perplexing issue. The code functioned flawlessly in Stackblitz but when I attempted to run it on my local system, an error surfaced: Type 'string' is not assig ...

angular2 Formatting Dates in Material 2 Datepicker

I'm currently utilizing the Angular Material datepicker in my angular4 project. I am looking for a way to format the selected date in the input box with a shorter format such as "May 29, 2017" instead of the current display which is "29/05/2017". Can ...

routerLinkActive maintains its active state even after another link has been clicked

<ul> <li routerLinkActive="active"><a routerLink="/">One</a></li> <li routerLinkActive="active"><a routerLink="/somewhere">Two</a></li> </ul> Upon clicking the link Two, both links are being hi ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

Efficient code for varying layouts of disabled Angular Material buttons

I've been wondering if there's a simpler way to customize the appearance of a disabled button using Angular Material. Currently, I achieve this by utilizing an ng-container and ng-template. While this method gets the job done, the code is not ve ...

How to avoid truncating class names in Ionic 4 production build

I have been working on an ionic 4 app and everything was going smoothly until I encountered an issue with class names being shortened to single alphabet names when making a Prod build with optimization set to true. Here is an example of the shortened clas ...

What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code? Here's what I have ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...