这两个事件在angular2中有什么区别

时间:2016-10-02 08:20:50

标签: angular

这两个事件在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来说是新手。

1 个答案:

答案 0 :(得分:2)

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

此处(recipSelected)自定义事件(不是内置的javascript事件)。通常情况下,每当您要触发任何事件时,send data孩子发送到父级,或者只要您希望父组件中的fire a custom eventexecute any function 所以你需要在rb-recipes-list component内使用 EventEmitter 输出 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.

   }

}

<强> parentController

<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(){}
}