Angular's 'exportAs' Feature: A Practical Guide to Sharing Component State

Photo by Andrew Moca on Unsplash

Angular's 'exportAs' Feature: A Practical Guide to Sharing Component State

Sharing Component State Made Easy

Play this article

Table of contents

In Angular when we build components with public properties or the state to share with others, some options come into our heads to solve it:

All options are valid, but we miss another way to share our component state in the template is using the exportAs property.

The exportAs

The exportAs property takes the Component or Directive name instance to make it available in the template.

  selector: 'app-country',
  templateUrl: './country.component.html',
  styleUrls: ['./country.component.css'],
  exportAs: 'countryContext'

It gives us access to the component instance, using a local variable in the template. For example, we create the variable #country to point to the exportAs: countryContext to access the CountryComponent instance, and we can use all public methods and properties anywhere in the template:

<div >
  From outside!
<app-nice-gif [selected]="country.selected"></app-nice-gif>
<app-country #country="countryContext">  <app-country-flag [selected]="country.selected"></app-country-flag>
  <app-country-flag [selected]="country.selected"></app-country-flag>
  <app-country-flag [selected]="country.selected"></app-country-flag>
  <app-banner [selected]="country.selected"></app-banner>


Using the exportAs help us not require changing the code in our components to inject a service o component as a dependency. The local variable gives the component access to all public methods or properties from the component only in the template.