Clear concept of EventEmitter Class

前端 未结 2 1648
温柔的废话
温柔的废话 2021-01-24 10:42

code into child component mycomponent.ts

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

@Component({
  selector: \'app-mycomponent\         


        
相关标签:
2条回答
  • 2021-01-24 11:01

    The Childcomponent emits a click event. The click event of your childcomponent is emitting a String, as you defined here:

     @Output() clicked = new EventEmitter<string>();
    
      clickchild() {
        this.clicked.emit('This is Child Component Code!');
      }
    

    The payload of the event (a string in this case), can then be accessed by the parameter $event. You subscribe in your parent component to the click event by:

    <app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
    
    onClicked(value: string) {
        this.childdata = value;
    }
    

    So the child component emits a click event, but it has to be recognized by the parent component (utilizing subscription), otherwise the parent would not know about the emitted event.

    See here for the docs: https://angular.io/api/core/EventEmitter

    Sagat

    0 讨论(0)
  • 2021-01-24 11:20

    During the click event of the child, one might want to notify the parent component that the child is being clicked. That is why we listen to the clicked event of the child in the parent. But the action that has to be done can (in your case it is to set some local state of a member) be done in either of the parent or the child depending on the app's need and properties that have to read or modified [because they might be present either the child or parent depending on the app architecture].

    If you prefer the parent component need not the notified by the child's click, its better you don't listen to it and make appropriate changes in the child event listener itself.

    0 讨论(0)
提交回复
热议问题