Vittal Kolla
Vittal Kolla

Reputation: 21

Angular Child to Parent interaction

Here I am emitting an event from child and was trying to display it in Parent HTML, but I don't see this working. Here 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>

In the above code, when I am displaying ParentComponent.HTML, I am not seeing {{fromChildMessage}} not getting printed in Browser and also I am not seeing {{childMessage}} when I display ChildComponent.HTML. Am I missing something here?

Upvotes: 1

Views: 107

Answers (1)

Skywolfmo
Skywolfmo

Reputation: 44

In the child component set the EventEmitter to string

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

then on the parent component:

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

Read More On: https://medium.com/@Zeroesandones/emit-an-event-from-a-child-to-parent-component-in-angular-9-7c3690c75f6

Upvotes: 0

Related Questions