[转]angular2之@Output, EventEmitter

本文转自:https://www.jianshu.com/p/f2768f927c86

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 传过来的。

作者:CK110

链接:https://www.jianshu.com/p/f2768f927c86

來源:简书

简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。