DEV Community

Collins Mutai
Collins Mutai

Posted on • Edited on • Originally published at builtin.com

How to Pass Data With EventEmitter in Angular

@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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
  }
}

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

@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>
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

Reference:
Sharing data between child and parent directives and components

Top comments (0)