Angular @Input() and @Output()

Praveen Kumar Palai
Rural Script
Published in
2 min readJan 29, 2020

Angular is a great framework for building fast and robust Web Apps, thanks to the multiple code splitting techniques. The features of angular as framework are just amazing. Every piece of code has a special purpose and with minimal repetition.

Cool, so talking of non-repetitive code brings us to yet another great feature of angular i.e. modular programming using Components.

Components provide us a great way to split code, mostly that is repetitive. Examples could include modals, toasts, forms, custom fields etc. There are innumerable applications.

Great! so we break our modules into components. Now our application has modules which are further broken down into components.

Now? How do we pass data between these components?

Okay! so basically the three most important ways to transfer data between components are:

  1. @ViewChild()
  2. @Input() and @Output() (Only if the components have parent child relationship)
  3. Services

One can easily pass data from parent to child components or vice-versa using the @Input, @Output decorators and the EventEmitter.

Let’s explain them one by one.
@Input() is used to link a property of one component (generally child component) to another component (generally parent component).

Whereas @Output() is used to link a property of a child component and emit it through the EventEmitter. So whenever the child component needs to pass some data to the parent it can do so by emitting it through the event emitter.

To cut it short and simple @Input() is used to pass data from parent to child component and @Output() is used to pass data from child to parent.

Let take an example to explain the same:

Child Component (JS)

Parent Component (HTML)

Here requestData is used to pass data from parent component to child component and is passed using property binding using [] brackets.

And requestInfo is used to emit data from child component to parent component and is mapped in the parent component using event binding using () brackets.

Bindings in Parent Component

The way to think about these two different ways of binding is in terms of inputs and outputs.

  1. With the [] we are binding to an input of a Component.
  2. With the () we are binding to an output of a Component.

This is what we call one-way data binding, since data only flows one way, either into or out of a component.

Conclusion

To summarise @Input() and @Output() are used to pass data between parent child components.

We will know more about the other two ways in the next upcoming articles. If you are still interested you can take a look the article below.

You can read more about @ViewChild() and Services here.

If you liked what you read do clap and please comment if you have any questions.

--

--