2016-10-02 52 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

相關問題