Data sharing between Angular Components

Data sharing between parent and child components is one of the fundamental concepts in Angular. Angular provides more than one correct way to do the data sharing between components as discussed below.

Passing data from Parent component to Child component using Input tag

This is perhaps the most straightforward and simplest way of passing data in angular. This can be done using @Input() tag as shown below.

Child Component:

Child component example code

Parent Component:

Parent component example code

Passing data from Child component to Parent component using Output tag

Similar to the @Input() tag, Angular also provides an @Output() tag, which is used to emit data from the child component to parent component using an eventEmitter .

Child Component:

Parent Component:

Passing data from Child component to Parent component using ViewChild

ViewChild tag in Angular allows us to inject child component into a parent component. This allows the parent to have access to the child’s public properties and functions. However, the child component is not available to the parent until the view has been initialized.

Hence, in order to access the child we need to use angular lifecycle hook AfterViewInit() .

Child Component:

Parent Component:

Full Stack developer. Angular | .Net | https://raghukaranam.com/