@Output()
To pass data from child to a parent component we use @Output() decorator. EventEmitter() class must be added to the @Output decorator to emit event and notify the parent of the change. A good example is when passing form input values from child to parent component.
We can configure a method in the child to raise an event when a user types into the input field.
export class ChildComponent {
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
}
In the child's template we use template reference variable
to reference the input field and then pass the value of the property to a button click handler.
<label for="item-input">Add an item:</label>
<input type="text" id="item-input" #newItem>
<button type="button" (click)="addNewItem(newItem.value)">Add to parent's list</button>
With event binding, we connect the event emitter in the child to the method in the parent. The $event contains the data from the input in the child template
<child-component (newItemEvent)="addItem($event)"></child-component>
export class ParentComponent {
items = ['item1', 'item2', 'item3', 'item4'];
addItem(newItem: string) {
this.items.push(newItem);
}
}
Now that we have access to this data we can display it in the parent component. With the help of **ngFor* to iterate the items in an array and render them in a list in the ui.
<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>
@Input()
Similarly we can pass data from parent to child. An @Input() decorator is a added to a child component. The property that the @Input() decorates receives its value from the parent. Using interpolation, we can pass the property to the child component template.
@Input() item = ''; // decorate the property with @Input()
<p>
Today's item: {{item}}
</p>
Next we use property binding to bind the property in the parent component's template. The value in the parent is the one we binding to.
<child-component [item]="currentItem"></child-component>
export class ParentComponent {
currentItem = 'Television';
}
Reference:
Sharing data between child and parent directives and components
Top comments (0)