DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Share Component State with 'exportAs’ in Angular
Dany Paredes
Dany Paredes

Posted on • Originally published at danywalls.com

Share Component State with 'exportAs’ in Angular

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'
})
Enter fullscreen mode Exit fullscreen mode

It give us access to the component instance, using local variable in the template. For example, we create the variable #country to point to the exportAs: countryContext to access the CountryComponent instance and use it 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>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

DEV

Thank you.

Β 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.