Tuesday, January 1, 2019

exportAs in Directive

How to create reference variable for a directive?

The way to reference a component is by using template reference variable. We can reference directives the same way.

In order to give the templates a reference to a directive we use the exportAs attribute. This will allow the host element (or a child of the host element) to define a template variable that references the directive using the #var="exportName" syntax.
Let’s add the exportAs attribute to our directive:

@Directive({
 selector: '[popup]',
 exportAs: 'popup',
 })
 export class PopupDirective {
 @Input() message: String;

 constructor(_elementRef: ElementRef) {
 console.log(_elementRef);
 }

 @HostListener('click') displayMessage(): void {
 alert(this.message);
 }
 }

And now we need to change the two elements to export the template reference:

template: `

 message="Clicked the message">

 Learning Directives


 This should use our Popup diretive




 message="Clicked the alarm icon">

No comments:

Followers

Link