Component Parent Child communication
Sending data to a Child Component
Configuring the child component
import Input and then decorate the property with @Input(), as in the following example.
src/app/item-detail/item-detail.component.ts import { Component, Input } from '@angular/core'; // First, import Input export class ItemDetailComponent { @Input() item = ''; // decorate the property with @Input() }
Next, in the child component template, add the following:
src/app/item-detail/item-detail.component.html
<p> Today's Product is : {{item}} </p>
Use property binding to bind the item property in the child to the currentItem property of the parent.
src/app/app.component.html
<app-item-detail [item]="currentItem"></app-item-detail>
In the parent component class, designate a value for currentItem:
src/app/app.component.ts
export class AppComponent { currentItem = 'Television'; }
Result:
item-detail works!
Today's Product is : Television
Sending data to a Parent Component
The @Output() decorator in a child component or directive allows data flow from the child to the parent.
Configuring the child component
Import Output and EventEmitter in the child component class:
import { Output, EventEmitter } from '@angular/core';
In the component class, decorate a property with @Output(). The following example newItemEvent @Output() has a type of EventEmitter, which means it's an event.
src/app/item-output/item-output.component.ts
@Output() newItemEvent = new EventEmitter<string>();
Create an addNewItem() method in the same component class:
src/app/item-output/item-output.component.ts
export class ItemOutputComponent {
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
}
Configuring the parent's template
In the parent's template, bind the parent's method to the child's event.
Put the child selector, here <app-item-output>, within the parent component's template, app.component.html.
src/app/app.component.html
<app-item-output (newItemEvent)="addItem($event)"></app-item-output>
To see the @Output() working, add the following to the parent's template:
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
Result:
Comments
Post a Comment