2016-10-02 54 views
0

这两个事件之间的区别是什么在angular2这两个事件之间的区别:是什么在angular2

<rb-recipes-list (recipeSelected)="selectedRecipe = $event"></rb-recipes-list> 

<rb-recipe-item [recipe]="recipe" (click)="onSelected(recipe)"></rb-recipe-item> 

而且他们为什么不能写同样的方式。他们有什么关系。

下面都写在同一组件:

@Output() recipeSelected = new EventEmitter<Recipe>(); 

    onSelected(recipe: Recipe) { 
     this.recipeSelected.emit(recipe); 
     console.log(recipe); 
     } 

是新来的angular2。

回答

2
<rb-recipes-list (recipeSelected)="selectedRecipe = $event"></rb-recipes-list> 

这里(recipSelected)自定义事件(不是内置的JavaScript事件)。通常当你想从孩子触发任何事件和send data母公司或当你在父组件要fire a custom eventexecute any function所以你需要,如下所示内rb-recipes-list componentEventEmitter输出的API声明它,

import {Component, EventEmitter, Output} from '@angular/core'; 
@Component({..}) 
export class RbRecipesListComponent{ 
    @Output rbRecipesList = new EventEmitter();   //<<<=== way to declare custom event 

    // Then you can fire this anywhere like this, 
    // 1st way 

    somefun(){ 
    this.rbRecipesList.emit('Angular2')  

    //rbRecipesList now emits value(Angular2) which will be received 
    //by $event defined in parentController eg. (recipeSelected)="selectedRecipe = $event" 
    // So Angular2 will be assinged to selectedRecipe variable. 

    } 

} 

OR

parentControll呃

<rb-recipes-list (recipeSelected)="onSelected($event)"></rb-recipes-list> 
                 //<<<==changed line 

export class parentController(){ 
    onSelected(value){ 
     this.selectedRecipe=value;      //<<<===Angular2 will be assigned to selectedRecipe 
    } 
} 

import {Component, EventEmitter, Output} from '@angular/core'; 
    @Component({..}) 
    export class RbRecipesListComponent{ 
     @Output rbRecipesList = new EventEmitter();  //<<<=== way to declare custom event 

     // Then you can fire this anywhere like this, 
     // 2st way 

     somefun(){ 
     this.rbRecipesList.emit('Angular2')  

     //rbRecipesList now emits value(Angular2) which will be received by $event 
     // This time onSelected() function will be fired at a same time 
     // So Angular2 will be assinged to selectedRecipe variable. 

     } 

    } 

<rb-recipe-item [recipe]="recipe" (click)="onSelected(recipe)"></rb-recipe-item> 

这是正常的的JavaScript(Angular2定义)单击事件。所以一旦rb-recipe-item点击,onSelected()将在父母控制器中被解雇。

export class parentController(){ 
     onSelected(){} 
} 
+0

再次感谢。是的,你的解释很清楚,尽管我不得不经过一遍。 谢谢。 –

+1

欢迎!是的,它是一个相当长的但值得去阅读以便更好地理解。 – micronyks

相关问题