A
src/app/components/contains/contain1.ts
import { Component,Output ,EventEmitter} from '@angular/core';
@Component({
selector: 'contain1',
template: `
<div>
<h3> contain1 </h3>
<div (click)="onChecked()" >
<button value="123"></button>
</div>
</div>
`})
export class Contain1 {
note = 'EventEmitter test'
@Output() checked = new EventEmitter();
onChecked(){
this.checked.next("next:"+this.note); //过时
this.checked.emit("emit:"+this.note);
}}
B
src/app/app.component.ts
import { Component } from '@angular/core';
import '../../public/css/styles.css';
import { Contain1,Contain2 } from './components/contains'
@Component({
selector: 'my-app',
directives:[ Contain1,Contain2 ],
template:`
<contain1 (checked)="showChecked($event)"></contain1>
<contain2></contain2> `,
styles: [require('./app.component.css')]})
export class AppComponent {
showChecked(note:String){
console.log(note);
}}
说明
A :
- @Outpout 定义一个输出
- onChecked(), A 中的自定义方法,通过emit,触发@Outpout
B: 使用 A 中定义的 @Output(),$event 必须,$event 是B 中通过emit 传过来的。