Sending data from child to parent component (@Output and EventEmitter)
Configuring the child component
The @Output()
decorator in a child component, CardComponent
lets data flow from the child to the parent, AppComponent
.
The CardsComponent
uses the @Output()
property to raise an event to notify the parent of the change.
To raise an event, an @Output()
must have the type of EventEmitter, which is a class in @angular/core
that you use to emit custom events.
In the CardComponent
, decorate a property with @Output()
. The following example titleEvent$
@Output()
has a type of EventEmitter, which means it’s an event.
Create an onAddCard()
method in CardsComponent
export class CardComponent {
@Output() titleEvent$ = new EventEmitter<string>();
onAddCard(title: string): void {
this.titleEvent$.emit(title);
}
}
Configuring the child template
...
<section>
<mat-form-field appearance="fill">-->
<mat-label>Title</mat-label>
<input type="text" matInput #cardTitle>
</mat-form-field>
<button mat-raised-button color="primary" (click)="onAddCard(cardTitle.value)">Add Card</button>
</section>
...
cardTitle is a template variable. Template variables help you use data from one part of a template in another part of the template. Template variable are prefixed by #
Configuring the parent template
The event binding, (titleEvent$)='addCard($event)'
, connects the event in the child, titleEvent$
, to the method in the parent, addCard()
.
The $event
contains the data that the user types into the input element in the child template UI.
<app-card [titles]="cardsTitle" (titleEvent$)="addCard($event)"></app-card>
Configuring the parent component
Push new card title received from child component.
export class AppComponent {
cardsTitle: string[] = ['Maia', 'Dylan', 'Minoru', 'Amarachi', 'Ceallagh'];
addCard(title: string) {
this.cardsTitle.push(title);
}
}