2016-10-02 7 views
0

angular2におけるこれら2つのイベントの違いは何ですかにおけるこれら2つのイベントの違いは何ですか:angular2

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

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

そして、なぜ彼らは同じように記述することはできませんが、 。彼らはどう関係しているのですか?

次は同じコンポーネントで書かれている:angular2に新しい

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

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

アム。

答えて

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

(recipSelected)カスタムイベント(ビルトインないjavascriptのイベント)です。一般的に、あなたは親に子から任意のイベントとsend dataを発射する場合、またはあなたが親コンポーネントfire a custom eventexecute any functionにいつでもだから、以下に示すように持つEventEmitter出力 APIとrb-recipes-list component以内にそれを宣言する必要があるときは、

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