<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