The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types?

I have an object

const amount = { currenty: 'USD', total: '10.25' };
that I need to emit to the parent component.

export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}

within the emitter function

this.childEventEmitter.emit(amount);
// It's not working

Error: Argument of type { currency: 'USD', total: '10.25' } is not assignable to parameters of type string.

Answer №1

After discovering the solution on my own, I am providing an answer to my previous query related to the error message "Type 'EventEmitter' is not generic" in Angular. The fix involved importing EventEmitter from @angular/core instead of Protractor.

I appreciate all the feedback and comments received on this matter.

Answer №2

@Output() broadcastChildEvent: EventEmitter<{currenty: string, total: string}> = new EventEmitter<{currenty: string, total: string}>();

Answer №3

One reason for the error could be due to Typescript flagging incompatible types. You can resolve this by either:

@Output() childEventEmitter = new EventEmitter<{currenty: string, total: string}>();

Alternatively,

@Output() childEventEmitter = new EventEmitter<any>();

Answer №4

A straightforward method to transmit various parameters via events.

@Output() childEventEmitter: EventEmitter<any> = new EventEmitter<any> ();

Answer №5

Describing my unique situation here, just in case someone encounters a similar issue.

I faced a problem where I was attempting to directly call the Output callback from HTML:

Child Component

...
 @Output() isCategorySelected: EventEmitter<any> = new EventEmitter<any>();

Child Component HTML

 <option *ngFor="let category of todoCategories" [value]="category"
                    [selected]="isCategorySelected(category)">{{category}}
                </option>

Parent Component HTML

<app-child (isCategorySelected)="myCategorySelectorFunc($event)"></app-child>

Solution

To resolve this issue, I had to create another method within the Child component and trigger the output from there:
...
 @Output() isCategorySelected: EventEmitter<any> = new EventEmitter<any>();

 public onCategorySelected(category: string): void {
    this.isCategorySelected.next(category);
 }

Child Component HTML

 <option *ngFor="let category of todoCategories" [value]="category"
                    [selected]="onCategorySelected(category)">{{category}}
                </option>

OR

 <option *ngFor="let category of todoCategories" [value]="category"
                    [selected]="isCategorySelected.next(category)">{{category}}
                </option>

Conclusion

It is important to note that EventEmitter, BehaviorSubject, Subject cannot be directly called as methods from HTML.

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

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

Resolving Modules: Using NPM to Install the Typescript Package Directly from Github

Recently, I decided to branch out and customize an existing npm package built in TypeScript to cater specifically to my unique requirements. I discovered that I could also install packages from GitHub branches using npm without any issues. However, after ...

I am trying to figure out how to retrieve the name of the property that is bound to [(ngModel)] in Angular 6

Here is a custom component example: <form-text [(ngModel)]="dataItem.prop1"> </form-text> Is there a way to extract the property name "prop1" from the class in this scenario? @Component({ selector: 'form-text', template ...

Angular form retains the previous value when saving

I encountered an issue with my form component where it displays previous values instead of updated ones during a save operation. The strange part is that if I close the form and reopen it, the new values are then shown correctly. It seems like the problem ...

TypeScript is throwing an error about a missing property, even though it has been defined

Within the PianoMK1Props component, there is a prop known as recording which accepts an object with specific properties. The structure of this object is defined like so(the state variable): const [recording, setRecording] = useState({ mode: "REC ...

Angular 14: Trouble with ngFor after latest update - Type 'unknown' causing issues

Just updated my project to angular version 14.0.4 Within the html of a component, I have the following code: <div class="file" *ngFor="let file of localDocumentData.files; index as i;"> <div class="card"> ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

Struggling with consolidating values in an array of objects - seeking assistance with Javascript

Currently, I am handling a project where I receive data in the form of an Object Array. My task is to merge values with the same key into one key and convert the values into an array of strings. Below is the sample data I am working with: inputArray = [ ...

What role does the @Input statement in the HeroDetailComponent class serve in the Angular 2 Quickstart tutorial?

Looking at the multiple components part of the Angular 2 Quickstart tutorial, we see how a component is separated from the AppComponent to enhance reusability and testing convenience. You can try out the example live demo here. In this scenario, users ar ...

Exploring the world of Jasmine and Angular: How to effectively mock nested methods within the Class being tested

Hello esteemed community... I have encountered a perplexing issue that appears straightforward, but has eluded my attempts at resolution... The challenge I am facing involves testing a Controller-Class in Angular. This particular codebase is laden with d ...

Facing the dreaded "ECONNREFUSED" error when trying to connect NodeJS and InfluxDb

I'm encountering an issue when trying to connect to my InfluxDB instance running in a Docker container. To get the InfluxDB image, I used the following command: docker pull influxdb:2.4.0 When I run it locally using Docker Desktop, everything works ...

Angular nested routes allow for creating more complex and dynamic

I'm facing an issue with setting up nested routes in my myfile.routing.module.ts file. Whenever I try to access a specific route, it keeps redirecting me back to the home page. Below is the snippet of my code: routing.module.ts . . . const routes: R ...

Multiplication table creation in Angular with ngFor

I am attempting to generate a table based on the input value. However, when I display the result, only the last value is shown instead of the entire result due to it being within a for loop. Below is the code from my multiplytable.component.ts file: expor ...

What is the best way to link a specific version of the @types package to its corresponding JavaScript package version?

Currently, I am in the process of working on a nodejs project with typescript 2.2 that relies on node version 6.3.1. My goal is to transition from using typings to utilizing @types. However, during this migration, several questions have arisen regarding th ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

Encountering errors while working with React props in typing

In my application, I am utilizing ANT Design and React with 2 components in the mix: //PARENT const Test = () => { const [state, setState] = useState([]); function onChange( pagination: TablePaginationConfig, filters: Record<string, ...

Extracting Date and Time Information from matDatepicker in Angular 6 Material

Below is the code snippet present in my html file: <mat-form-field> <input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"> <mat-datepicker-toggle matSuffix [for]="myDatepic ...

Angular 5: Steps to send an event from authguard to header in Angular application

I am struggling to send out an event from the authguard component to the header component. Event broadcasting setup @Injectable() export class BroadcastService { public subject = new Subject<any>(); sendMessage(message: string) { this.subjec ...