<rb-recipes-list (recipeSelected)="selectedRecipe = $event"></rb-recipes-list>
这里(recipSelected)
是自定义事件(不是内置的JavaScript事件)。通常当你想从孩子触发任何事件和send data
母公司或当你在父组件要fire a custom event
和execute 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.
}
}
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(){}
}
再次感谢。是的,你的解释很清楚,尽管我不得不经过一遍。 谢谢。 –
欢迎!是的,它是一个相当长的但值得去阅读以便更好地理解。 – micronyks