Angular 2 @Output with (click)

ttm*_*tmt 1 typescript angular

我在这里有一个 plunker - https://plnkr.co/edit/QFB5eNQlRlXe7myrPsIs?p=preview

我知道这是一个愚蠢的例子,但我只是想使用(单击)和@Output 来获取工作示例。

我有一个计数器组件,它有两个按钮,增加和减少一个数字,另一个按钮,我想使用它在父组件上输出当前数字。

我知道愚蠢的例子,但只是想要一些简单的东西来学习@Output

import {Component} from '@angular/core'

@Component({
  selector: 'app',
  templateUrl: './src/app.component.html'
})

export class AppComponent {

  myCount: number = 5

  newCount: number

  constructor() {

  }

  countChanges(event) {
    this.myCount = event;
  }

  handleEventClicked(data){
    this.newCount = data
  }

}
Run Code Online (Sandbox Code Playgroud)

cyr*_*r_x 9

如果你使用Output装饰器,你需要两件事:

  1. 用它装饰的属性,它EventEmitter来自 '@angular/core' 包。
  2. 一种告诉输出发出值的方法。

对于具有简单单击事件的示例,您将执行以下操作:

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

@Component({ 
    selector: 'my-example',
    ...
})
export class MyExampleComponent {
    @Output()
    public myOutput = new EventEmitter<MouseEvent>();
    
    public handleClick(event: MouseEvent) {
        this.myOutput.emit(event);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在您的模板中:

<div (click)="handleClick($event)">click me</div>
Run Code Online (Sandbox Code Playgroud)

从父组件,您可以将处理程序绑定到新创建的输出:

<my-example (myOutput)="parentHandleClick($event)"></my-example>
Run Code Online (Sandbox Code Playgroud)

您可以将您喜欢的任何数据传递给 EventEmitter,然后通过$event父级获取它。