Having trouble capturing emitted events from a child component in Angular 2+?

I have a question as a beginner. I'm trying to send a message from the child component to the parent component but for some reason, it's not working.

app.component.html

<app-cart-component> [items]="rootItems" (outputItems)="handleChange($event)" </app-cart-component>

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  rootItems = ['Apples', 'Bananas', 'Cherries']
  title = 'inputOutputEventemitter';

  handleChange($event){
    console.log("pushing item to rootItems" + $event)
    this.rootItems.push($event)
    
  }

}

cart-component.component.html

<input type="text" [(ngModel)]="newItem">
<button (click)='addToList()'> Add to List</button>

cart-component.component.ts

@Component({
  selector: 'app-cart-component',
  templateUrl: './cart-component.component.html',
  styleUrls: ['./cart-component.component.css']
})
export class CartComponentComponent implements OnInit {

  newItem = ''

  @Input() items = []
  @Output() outputItems = new EventEmitter<string>()

  constructor() { }

  ngOnInit(): void {
  }

  addToList(): void {
    this.items.push(this.newItem)
    
    this.outputItems.emit(this.newItem)

    console.log("from CartComponentComponent emitting" + this.newItem)
  }

}

Answer №1

Valery's solution appears to have successfully fixed the problem.

<app-cart-component [items]="rootItems" (outputItems)="handleChange($event)"></app-cart-component>

The line of code above from the HTML resolved the issue. Thank you, Valery.

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

The VueJS function is not defined

Looking for a way to fetch data from graphql in my vue project and store it in a variable. The function is asynchronous and the value of rawID needs to be awaited. However, there is a possibility that it could result in undefined, causing an error in the ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

How can we dynamically render a component in React using an object?

Hey everyone, I'm facing an issue. I would like to render a list that includes a title and an icon, and I want to do it dynamically using the map method. Here is the object from the backend API (there are more than 2 :D) // icons are Material UI Ic ...

Produce new lines of code using the vscode.window.activeTextEditor.edit method in Visual Studio Code

Hey everyone, I'm currently working on a vscode extension that can automatically generate template code based on the language you are using when you click a button. However, there seems to be an issue with the formatting of the generated code as it do ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...

The navigation function in Angular, this.router.navigate, is causing issues and

I've encountered a peculiar issue. There's a logout function that is activated whenever I receive a 401 response from any API I interact with. The function looks like this: constructor( private router: Router, ) {} logout(router1: Router ...

Tips for elegantly merging two Observables within an RXJS pipeline

I am working on developing a log viewer using Angular. Upon user entry, I aim to load historical logs and also begin monitoring for new logs. Users have the ability to filter logs using a simple form that emits a query object. Each time the query changes, ...

Managing table columns with Angular 6: Tips and Tricks

I am attempting to display items from a table using the following structure: columns: any[] = [ { field: 'title', header: 'Type of Leave' }, { field: 'nbDay', header: 'Number of Days' }, { field: ' ...

Can multi-page applications be developed using Angular?

As I contemplate developing a food ordering application similar to Zomato, I have observed that Angular-like routing is used on certain pages, specifically during the ordering process after selecting a restaurant. Unlike other sections where server routing ...

Can you please provide instructions on how to obtain the TypeScript definitions file for a specific version of Jquery, such as 3.2.1

As I navigate my way through TypeScript, I find myself in need of accessing type definitions for a jQuery project in Visual Studio. The project currently utilizes jquery version 3.2.1, and I'm on the lookout for TypeScript type definitions for it. Af ...

Tips on rotating a material-ui icon

Having trouble rotating a material-ui icon using the CSS animation property. Can anyone assist in identifying what may be causing the issue? Link to example code sandbox I'm looking for a continuously rotating icon. ...

How can I modify the icon once the accordion summary is expanded?

How can I switch the icon based on whether the accordion is expanded or not? I noticed that on the material ui page there is a CSS class called .Mui-expanded which can detect whether expanded={true} or false. But, how do I utilize this to change the ...

Navigating through nested Firebase realtime DB queries using await/async techniques

In the process of developing a Firebase function (Gist), I encountered a challenge that I'm seeking assistance for. The function starts by querying a realtime database reference (events) using this code: await admin.database().ref('/events_geo ...

How to simulate a particular class from a node package using Jest mocks

In my project, I'm looking to specifically mock the Socket class from the net node module. The documentation for this can be found here. Within my codebase, there is a class structured similar to the following... import { Socket } from 'net&apo ...

TypeScript Redux Thunk: Simplifying State Management

Seeking a deeper understanding of the ThunkDispatch function in TypeScript while working with Redux and thunk. Here is some code I found: // Example of using redux-thunk import { Middleware, Action, AnyAction } from "redux"; export interface ThunkDispatc ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...

What is the best way to synchronize API definitions between the server and client using TypeScript?

My setup involves a server (TypeScript, NestJS) and a client (TypeScript, Angular) that communicate with each other. Right now, I have the API response DTO classes defined in both the server to output data and in the client to decode the responses into a ...

Working with Angular: Managing an Array of Objects

After retrieving an array of objects using the code snippet below: this.serviceOne.getRemoteData().subscribe( data => this.MyArray.push(data) ); I encounter issues when trying to iterate through the array using the code snippet bel ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...