Fanis Prodromou
  • Blog
  • About
  • Blog
  • About
Search by typing & pressing enter

YOUR CART

12/26/2018 Comments

Component communication with exportAs property


Have you ever had the need two components to communicate each other? Of course you had!

I bet that when you hear components communication or components interaction, you automatically think of @input @output decorators. 

Say that we have two components, parent and child. You want the parent component to interpolate on its template a property from the child component. How can we do this?
​
  1. Make use of @output decorator.
    When the child emits an event, the parent will handle this, take the event arguments, assign the value on a another variable, and finally use that variable on the template interpolation. You don't say that is a short way :)

  2. Make use of @viewChild

  3. Make use of exportAs

What exportAs does?

A class has various access modifiers (private, public, protected etc.) and the instances of this class are affected by those modifiers. Think of public and private. If we have a class with two properties, the instance of this class can use only the public ones.

    
The instance with name parent can not use the property _anotherProperty because it's private.
Using the exportAs in your component, you are exporting all the public properties and methods

How to use the exportAs

Below is a list of some of the very well known component metadata:
  • selector
  • templateUrl
  • template
  • styleUrls
  • styles
There is one more! exportAs 
1) Add the exportAs property on the component decorator and add a name of your desire. The name is meaningful as you will got access to the component via this name

    
2) ​Create a template reference variable on the component's selector

    
The #childinstance is the template reference variable. In essence, with hash (#) we declare variable on the template.
On this variable, we assign the name child which is the name we chose when we decided to export the component.
We can now access the properties via the variable we've just created.

Find here a working example
​https://stackblitz.com/edit/parent-child-exportas
Comments
comments powered by Disqus

    Author

    I am a senior software engineer who loves scuba diving and hiking. A dog type person who owns two cats

    View my profile on LinkedIn

    Tags

    All Angular Angularjs General Graphql Ionic Javascript .net Nodejs Typescript

Proudly powered by Weebly