关于typescript:Angular 2 @Output with(单击)

Angular 2 @Output with (click)

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

我知道这是一个愚蠢的示例,但我只是想使用(单击)和@Output获得有效的示例。

我有一个计数器组件,其中有两个按钮,它们可以增加和减少一个数字,另一个按钮是我想用来在父组件上输出当前数字的。

我知道一个愚蠢的例子,但只想简单学习@Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
  }

}

如果使用的是Output装饰器,则需要两件事:

  • 装饰有它的属性,它是来自'@ angular / core'包的EventEmitter
  • 一种告诉输出发出值的方法。
  • 对于具有简单click事件的示例,您将执行以下操作:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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);
        }
    }

    并在您的模板中:

    1
    click me

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

    1
    <my-example (myOutput)="parentHandleClick($event)"></my-example>

    您可以将所需的任何数据传递给EventEmitter,然后通过父级中的$event进行获取。


    这里是工作示例,您只需要更改handleEventClicked

    https://plnkr.co/edit/GzEbtSg103eXVv03WSm4?p=preview


    尝试一下...

    child.component.html文件

    1
    <button class="btn btn-success" (click)="addCount();">add Count</button>

    child.component.ts文件

    1
    2
    3
    4
    5
    6
    7
    8
    @Output() myCountEmit = new EventEmitter(); // output Emitter variable
    count: Number = 0;

    // emit function
    addCount(){
    this.count++;
    myCountEmit.emit({'count': this.count , 'component' : 'child component'});
    }

    Parent.component.html文件

    1
       </app-child>

    Parent.component.ts文件

    1
    2
    3
    clickEvent(value) {
        console.log(value); // output emit result
      }