Understanding @Input, @Output and EventEmitter in Angular

To those who are new to Angular, the Input and Output decorators are a bit confused, especially when you are studying them by looking at example code. In this article, I will try to explain them in the simplest way.

A tool to exchange data

First of all, the idea of Input and Output is to exchange data between components. They are a mechanism to send/receive data from one component to another.

Input is used to receive data in whereas Output is used to send data out. Output sends data out by exposing event producers, usually EventEmitter objects.

So when you see code like this

@Component({ selector: ‘todo-item’, …})export class TodoItemComponent { @Input() item @Output() onChange = new EventEmitter()}

that means

  • hey, I am expecting data being sent to me. I will receive it and store it into my item property
  • by the way, I will produce and send data out via the onChange property.

Let?s say you have a TodoList component that contains TodoItem component. In the TodoList template, you are expected to see

…<todo-item [item]=”myTask” (onChange)=”handleChange($event)”</todo-item>…

which means

  • TodoList puts data values in its myTask property and passes it to TodoItem
  • data emitted from TodoItem will be received and handled by the handleChange() function in TodoList

That?s it for the theory. Let?s have a look at the example.

@Input and @Output in action

Check out this example. Here I created 2 components, hello component nested inside the app component. The hello component has an Input and an Output

hello.component.ts@Component({ selector: ‘hello’, template: ` <h3 (click)=”onClick.emit(‘Neo’)”> … </h3> `})export class HelloComponent { @Input() myFriend: string @Output() onClick = new EventEmitter()}

It expects to receive a string value and stores it in the myFriend property.

@Input() myFriend: string

Every time you click on it, the Output property onClick will emit a string ?Neo? to the outside world.

<h3 (click)=”onClick.emit(‘Neo’)”>

Below is the app component

app.component.tsexport class AppComponent { ng = ‘Angular’ myName = ‘Neo’ upCase(st:string): void { … }}app.component.html<hello myFriend=”{{ ng }}” (onClick)=”upCase($event)”></hello><h3>My name is {{ myName }}</h3>

Note that the app component uses the hello tag in its template and does two things:

  • passing a string value ?Angular? to hello via its ng property

<hello myFriend=”{{ ng }}”

  • receiving the emitted value from hello and process that value by the upCase() function

<hello myFriend=”{{ ng }}” (onClick)=”upCase($event)”>

You can see the app in action here


No Responses

Write a response