Components Communication

Angular component, in most cases is not a separate unit and has to communicate with other components to exchange some information. Usually, components interaction takes place between components that are in child-parent relationship:

Component A and Component B can exchange information in three different ways:
a) by using reference variable:

Reference variable allows to control child from parent, but only within template.

b) by using @ViewChild decorator:

@ViewChild decorator enables to control child component from template as well as from class code. In this approach, it is mandatory to remember that access to the child is possible at the earliest when ngAfterViewInit function is calling.

c) by using @Input and @Output decorators:

@Input allows to provide some data to the child, @Output gives possibility to inform parent component that something has been changed.

In some scerios, it is also necessary to ensure communication between components that are located in different places in the application. In this case, the simpliest option to make it possible is to create a service that could be a broker between components. All components that need to exchange information should use the same service instance.

Leave a Reply

Your email address will not be published. Required fields are marked *