Thibs
Thibs

Reputation: 8288

Angular: template reference variable with directives

I read in the Angular docs that we can use a template reference variable on a custom component and we can get access to the public methods and properties of this component.

I tried the same on an element with a directive and it does not work.

<table #myTable my-directive>
    <tr>
       <th>Name</th>
    </tr>
    <tr>
        <!--test value is a prop of my directive -->
        <td>Some text: {{ myTable.testValue }}</td> 
    </tr>
</table>

Is it possible to use a template reference variable with a directive to get access to this directive's properties?

Upvotes: 1

Views: 2876

Answers (1)

Abinesh Devadas
Abinesh Devadas

Reputation: 1547

Yes, you can use exportAs property of Directive metadata declartion

@Directive({
  selector: '[my-directive]',
  exportAs: "myDirective"
})
export class MyDirective {
  name: string = "Hello World";
  constructor() { }
}

Then in your html you should access as follows

<div my-directive #t=myDirective>
  {{ t.name }}
</div>

Upvotes: 12

Related Questions