0
votes

I have two components child and parent components each having its own directory.

child folder

child.component.html

<p>{{message}}</p>
<button (click)="sendMessage()">SendMessage</button>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input('msg') message: string;
msg = 'I am child';
@Output('smEvent') sendMessageEvent = new EventEmitter<string>();
  constructor() { }

  ngOnInit(): void {
  }
  sendMessage() {

    this.sendMessageEvent.emit(this.msg);
  }


}

parent folder parent.component.html

<app-child [msg]="testMessage" (smEvent)="sendMessageEvent($event)"></app-child>
<p>{{msgs}}</p>

parent.component.ts

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

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

  testMessage = 'test';
  msgs = '';
  constructor() { }

  ngOnInit(): void {
  }
  sendMessageEvent($event) {
    console.log(' child => ' + $event.msg); //returns undefined
    this.msgs = $event.msg;
  }

}

app.component.html

<app-parent></app-parent>

I am able to do parent to child communication but in case of the child to parent communication, I am not able to do so. How can I able to communicate and what did I miss?

2

2 Answers

3
votes

Instead of

sendMessageEvent($event) {
    console.log(' child => ' + $event.msg); //returns undefined
    this.msgs = $event.msg;
  }

You can try with this:

sendMessageEvent($event) {
    console.log(' child => ' + $event);
    this.msgs = $event;
  }

That's because your $event is a string msg = 'I am child';. If you send an object like:

object = {
   msg: 'I am child'
};

You could use $event.msg

0
votes

According to angular.io, you can use the following way to Parent-child communication.

Child Component

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

@Component({
  selector: 'app-name-child',
  template: '<h3>"{{name}}"</h3>'
})
export class NameChildComponent {
  @Input()
  get name(): string { return this._name; }
  set name(name: string) {
    this._name = (name && name.trim()) || '<no name set>';
  }
  private _name = '';
}

Parent Component

import { Component } from '@angular/core';
@Component({
  selector: 'app-name-parent',
  template: `
  <h2>Master controls {{names.length}} names</h2>
  <app-name-child *ngFor="let name of names" [name]="name"></app-name-child>
  `
})
export class NameParentComponent {
  // Displays 'Dr IQ', '<no name set>', 'Bombasto'
  names = ['Dr IQ', '   ', '  Bombasto  '];
}

Go to the following link and learn more about "Pass data from parent to child with input binding" https://angular.io/guide/component-interaction