Dany Paredes
Danywalls | Angular ♥ Web

Danywalls | Angular ♥ Web

Share Components State with 'exportAs’ in Angular

Photo by Andrew Moca on Unsplash

Share Components State with 'exportAs’ in Angular

An alternative way to share components state

Dany Paredes's photo
Dany Paredes
·Sep 30, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • The exportAs
  • Recap

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.

@Component({
  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>
</div>
<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>
</app-country>

Recap

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.

 
Share this