通過 Output 事件發射器將資料從子節點傳送到父節點

事件 emitter.component.ts

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

@Component({
  selector: 'event-emitting-child-component',
  template: `<div *ngFor="let item of data">
               <div (click)="select(item)">
                 {{item.id}} = {{ item.name}}
               </div>
             </div>
            `
})

export class EventEmitterChildComponent implements OnInit{
  
  data;
  
  @Output()
  selected: EventEmitter<string> = new EventEmitter<string>();
  
  ngOnInit(){
    this.data = [ { "id": 1, "name": "Guy Fawkes", "rate": 25 }, 
                  { "id": 2, "name": "Jeremy Corbyn", "rate": 20 }, 
                  { "id": 3, "name": "Jamie James", "rate": 12 }, 
                  { "id": 4, "name": "Phillip Wilson", "rate": 13 }, 
                  { "id": 5, "name": "Andrew Wilson", "rate": 30 }, 
                  { "id": 6, "name": "Adrian Bowles", "rate": 21 }, 
                  { "id": 7, "name": "Martha Paul", "rate": 19 }, 
                  { "id": 8, "name": "Lydia James", "rate": 14 }, 
                  { "id": 9, "name": "Amy Pond", "rate": 22 }, 
                  { "id": 10, "name": "Anthony Wade", "rate": 22 } ]
  }
  
  select(item) { 
      this.selected.emit(item);
        
  }

}

事件 receiver.component.ts:

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

@Component({
    selector: 'event-receiver-parent-component',
    template: `<event-emitting-child-component (selected)="itemSelected($event)">
                </event-emitting-child-component>
                <p *ngIf="val">Value selected</p>
                <p style="background: skyblue">{{ val | json}}</p>`
})

export class EventReceiverParentComponent{ 
  val;
  
  itemSelected(e){
    this.val = e;
  }
}