Interacting between Angular Child and Parent components

I am facing an issue where I am trying to emit an event from a child component and display it in the parent HTML, but it doesn't seem to be working. Below is my code:

ParentComponent.ts


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

  parentMessage = "Hello from Parent";
  fromChildMessage: String;

  constructor() { }

  ngOnInit(): void {
  }

  fromChild($event){
    this.fromChildMessage = $event;
    console.log(this.fromChildMessage);
  }

}

ParentComponent HTML


<app-child [childMessage] = "parentMessage" (sendingToParent) = "fromChild($event)"></app-child>


<p>{{fromChildMessage}}</p>

ChildComponent.ts

import { EventEmitter } from '@angular/core';
import { Component, Input, OnInit, Output } from '@angular/core';

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

  @Input() childMessage: String;
  @Output() sendingToParent: EventEmitter<any> = new EventEmitter<any>();

  text: String = "Hello from Child";

  constructor() { }

  ngOnInit(): void {
  }

  sendParent(): any {
    this.sendingToParent.emit(this.text);
  }

}

ChildComponent HTML

<p>child works!</p>
{{childMessage}}

<button (click)="sendParent()">SEND</button>

When viewing ParentComponent.HTML, the {{fromChildMessage}} does not get printed in the browser, and similarly, {{childMessage}} does not show up when viewing ChildComponent.HTML. Am I overlooking something here?

Answer №1

To pass data from a child component to its parent, set up an EventEmitter with type string:

@Output() sendDataToParent: EventEmitter<string> = new EventEmitter<string>();

In the parent component, define a method to handle the event data:

receiveDataFromChild(eventValue){
    this.dataFromChild = eventValue;
    console.log(this.dataFromChild);
}

For more information, visit: https://medium.com/@UniqueURL/unique-slug-here

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

Firestore rules restrict access to the data, however the Angular project is still able to retrieve the collection - ERROR Error: Insufficient permissions or missing

I am currently working on an Angular project that is connected to a Firestore database. Within the database, there is a collection called users, and each document within this collection contains a nested collection named hugeCollection. I have updated the ...

Combining Multiple .ts Files into a Single File: A Simplified Application Structure with TypeScript 1.8

Currently, I am in the process of developing an Electron application and I have decided to implement TypeScript for this project. While TypeScript essentially boils down to JavaScript in the end, my familiarity with it makes the transition seamless. As of ...

customize your selections in p-multiselect with dynamic choices primeng angular 2

I am currently working on implementing the Primeng datatable. I have put together an array containing headers, fields, and options called headersList. Here is how it looks: { header: "Time", field: "time", options: "timeOptions" }, { header: ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

Tips on including text within PrimeNG speeddial option buttons?

Instead of icons, I would like to have text displayed in the options of my speed dial component. https://i.sstatic.net/I4Rx5.png This is what I am aiming for https://i.sstatic.net/0u5OP.png Thank you in advance ...

Creating a message factory in Typescript using generics

One scenario in my application requires me to define message structures using a simple TypeScript generic along with a basic message factory. Here is the solution I devised: export type Message< T extends string, P extends Record<string, any> ...

Do you believe this problem with transpilation has been properly reported to babel-jest?

I recently encountered a problem in the jest project regarding babel-jest transpilation. I added some code that appeared to be error-free, but caused transpilation to fail completely. Although the issue seemed related to a Typescript Next project, there a ...

Leveraging the power of RXJS and typescript for executing work conditionally between Server and Client Code

I am in need of a function that will assess various conditions to determine if an object is eligible for editing. These conditions may exist on both the server and client sides. Certain conditions should halt further validation and return a value. ...

Guide to including spinner in React JS with TypeScript

I need help with adding a spinner to a React component. The issue I'm facing is that the spinner does not disappear after fetching data from an API. Can someone please point out what I am doing wrong? Here is the code snippet: import React, { useSta ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

Linking all styles with Angular 2

Is it possible to apply a style when the exact nature of that style is unknown? Consider a scenario where I have a model containing string variables defining styles, as shown below: myStyle1:string="margin-left:10px"; myStyle2:string="margin ...

Upgrade your project from Angular 5 to Angular 9 using webpack

I want to share my experience, not ask a question! To upgrade dependencies in package.json: -Update all Angular dependencies to version 9 -Add these dependencies: "@angular-devkit/build-angular": "^0.900.4", "@angular-builders/cu ...

Testing an Angular component with @Input through unit testing

I am dealing with an angular component that utilizes an @input attribute and processes it in the ngOnInit. When writing unit tests for @inputs, I usually set the value using component.inputproperty=value. However, in this case, I cannot do so due to the ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Generate a byte array in JavaScript

How can a byte array be created from a file in JavaScript (or Typescript) to send to a C# WebApi service and be consumable by the C# byte array method parameter? Could you provide an example of the JavaScript code? The context here is an Angular 4+ applic ...

Encountered error when attempting to clone Angular project using npm: ELIFECY

Hi there, I'm facing an issue with cloning my Angular project. Whenever I try to run the frontend using IntelliJ or VSCode, I'm encountering this error message: C:\Users\developer.me\Downloads\TestClone\node_modules&bsol ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

What are some ways I can enhance the typography within Material UI?

Currently, I am in the process of developing a custom theme utilizing createMuiTheme. However, my application requires more typography variants than what Material UI provides out of the box. I need to extend the typography so that it aligns with my specifi ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

Creating an Angular 2 application within a Cordova project

I've been on the hunt for resources that break down using Angular 2 in a Cordova app, but it seems like there's a lack of straightforward explanations out there. For example, once I create a Cordova app with: cordova create sampleApp, should I na ...