Why use exportAs Property in Angular

Have you used exportAs property of a directive? It could be instrumental in working with public methods of a directive.

Let us say; you have created a custom directive to change the background colour of the host element on the mouse hover as below,


import { Directive, Input, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appChangebg]'
})
export class ChangebgDirective {

  constructor(private el: ElementRef) {

  }
  @Input() color;
  @HostListener("mouseover") applyColor() {
    this.changeColor(this.color);
  }

  @HostListener("mouseleave") removeColor() {
    this.changeColor(null);
  }
  changeColor(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }

}

The above custom directive changes the background colour of the host element. You can apply to a div as shown below,


const template = `
<div>
<h2>{{title}}</h2>
<div appChangebg [color]="'yellow'">{{message}}</div>
</div>
`

@Component({
  selector: 'app-root',
  template: template
})
export class AppComponent {
  title = 'Parent Component';
  message = "this is an amazing app";
}

Now let us assume there is a button on the template of the host element, and on click of that button, you directly wish to call public methods or use public properties of the custom attribute directive. For example, on the button click, you directly wish to set the background colour of the host element.

So, to access public properties and methods of the custom directive, Angular provides exportAs property.

You can use exportAs property with the directive as below,


@Directive({
  selector: '[appChangebg]',
  exportAs: 'changecolor'
})
export class ChangebgDirective {


Next, you can use it on the host element template as below,


const template = `
<div>
<h2>{{title}}</h2>
<div appChangebg [color]="'yellow'" #a='changecolor'>{{message}}</div>
<button (click)="a.changeColor('green')">Change Background</button>
</div>
`

@Component({
  selector: 'app-root',
  template: template
})
export class AppComponent {
  title = 'Parent Component';
  message = "this is an amazing app";
}

Now on the button click, you can directly access public method changeColor to change the background colour of the host element.

So, you will find exportAs property very useful, when you publish custom directives as a library. I hope you find the post useful. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com