简体   繁体   English

angular2 rc6 事件发射器 - 父子交互示例

[英]angular2 rc6 event emitter - parent child interaction example

I am looking for an example that explains how parent child interaction using event emission works in angular2-rc6 version (that no longer makes use of directives).我正在寻找一个示例来解释使用事件发射的父子交互如何在 angular2-rc6 版本(不再使用指令)中工作。 Most of the links available online seem to have the directives tag functional (older version of angular2).大多数在线可用链接似乎都有指令标签功能(angular2 的旧版本)。

See this link on COMPONENT INTERACTION请参阅组件交互上的此链接

VoterComponent选民组件

import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
  selector: 'my-voter',
  template: `
    <h4>{{name}}</h4>
    <button (click)="vote(true)"  [disabled]="voted">Agree</button>
    <button (click)="vote(false)" [disabled]="voted">Disagree</button>
  `
})
export class VoterComponent {
  @Input()  name: string;
  @Output() onVoted = new EventEmitter<boolean>();
  voted = false;
  vote(agreed: boolean) {
    this.onVoted.emit(agreed);
    this.voted = true;
  }
}

VoteTakerComponent VoteTaker 组件

import { Component }      from '@angular/core';
@Component({
  selector: 'vote-taker',
  template: `
    <h2>Should mankind colonize the Universe?</h2>
    <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
    <my-voter *ngFor="let voter of voters"
      [name]="voter"
      (onVoted)="onVoted($event)">
    </my-voter>
  `
})
export class VoteTakerComponent {
  agreed = 0;
  disagreed = 0;
  voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
  onVoted(agreed: boolean) {
    agreed ? this.agreed++ : this.disagreed++;
  }
}

Hope this helps!!希望这可以帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM