总的来讲,Input 用来进行属性绑定,将父组件的属性传给子组件,即有数据传进组件;Output 用来在事件绑定时,子组件将事件传给父组件进行处理,既有数据传出组件;如图: typescript
先来看串代码:app-child.component.tsapp
import {Component, Input, EventEmitter, Output } from '@angular/core'; @Component ({ selector: 'app-child', template: `<button class="btn btn-primary" (click)="handleclick()">Click me</button>` }) export class AppChildComponent { handleclick () { console.log('hello,Child'); } }
在这个子组件模板中,有个按钮,绑定了 click 事件;将这个模板放进根模块 AppComponent.ts 中为:函数
import {Component } from "@angular/core"; @Component({ selector: 'app-root', template: `<app-child></app-child>` }) export class AppComponent implements OnInit{ ngOnInit(){ } }
当把 <app-child></app-child> 放进 AppComponent 中,组件之间产生了父子关系,AppComponent 为父组件;当点击按钮时,console 会打印出 "hello,child",这是一个很常见的事件绑定。如今咱们想一想:若是想在子组件按钮点击事件中执行父组件的功能,咱们该怎么作呢? 要作到这一点,须要将事件从子组件中发送到父组件,因而,咱们引入 'angular/core' 模块中的 Output 和事件传送 EventEmitter;如今咱们发出事件,而且将事件传参;this
import {Component, EventEmitter, Output } from '@angular/core'; @Component ({ selector: 'app-child', template: `<button class="btn btn-primary" (click)="valueChanged()">Click me</button>` }) export class AppChildComponent { @Output() valueChange = new EventEmitter(); Counter = 0; valueChanged() { this.Counter = this.Counter + 1; this.valueChange.emit(this.Counter); } }
咱们作了以下操做:code
import {Component } from "@angular/core"; @Component({ selector: 'app-root', template: `<app-child (valueChange)="displayCounter($event)"></app-child>` }) export class AppComponent implements OnInit{ ngOnInit(){ } displayCounter(count){ consoloe.log(count); } }
在父组件的模板的事件绑定中,注意绑定的是 valueChange,它是从子组件传递过来的事件传送实例;这里定义了 displayCounter() 函数,在子组件按钮点击事件触发的时候,父组件的这个功能也会执行,打印出 counter 的值; 以上,就实现了在子组件按钮点击事件发生后,父组件的功能也会执行。component