2

In angular 2 when #elementReference is used with *ngIf the reference to the element remains undefined even after *ngIf expression evaluates to true. In following example the input's value will not be shown.

<input *ngIf="true" type="text" #myRef (input)="a = 'b';" class="form-control input-lg">
<pre> {{ myRef?.value }} </pre>

But however following will work (surprised me).

<div *ngIf="true">
          <input type="text" #myRef (input)="a = 'b';" class="form-control input-lg">
          <pre> {{ myRef?.value }} </pre>
      </div>

My question is how do I get the #reference to the element from anywhere in the template when used with *ngIf like directives.

Lekhnath
  • 4,532
  • 6
  • 36
  • 62
  • Possible duplicate of [Angular2, \*ngIf and local template variables](http://stackoverflow.com/questions/36642487/angular2-ngif-and-local-template-variables) – Mihai Răducanu Jun 25 '16 at 07:42

2 Answers2

1

The documentation recommends against using elementRef in situations where data binding is possible:

Use this API as the last resort when direct access to DOM is needed. Use templating and data-binding provided by Angular instead.

Solution using data-binding:

<input *ngIf="true" type="text" [(ngModel)]="myModel" (input)="a = 'b';" class="form-control input-lg">
<pre> {{ myModel }} </pre>
Mihai Răducanu
  • 12,225
  • 4
  • 22
  • 31
  • `elementRef` is not being used here. `#myRef` is a [template reference variable](https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars) which is fine to use. Template reference variables would fall under 'templating' in the docs you quoted. – Michael Jun 25 '16 at 01:25
  • See this question for the explanation of why *ngIf and #refs don't work on the same element: http://stackoverflow.com/questions/36642487/angular2-ngif-and-local-template-variables#36651625 – Mihai Răducanu Jun 25 '16 at 07:41
0

This behaviour would be caused by the fact that

<div *ngIf="show"></div>

is syntactic sugar for

<template [ngIf]="show">
  <div></div>
</template>

Template reference variables can only be used

on the same element, on a sibling element, or on any child elements.

Your example looks like this desugared:

<template [ngIf]="true">
  <input type="text" #myRef (input)="a = 'b';" class="form-control input-lg">
</template
<pre> {{ myRef?.value }} </pre>

As you can see, the reference variable #myRef is not a sibling of the pre element that tries to use it and so it won't work.

Michael
  • 5,994
  • 7
  • 44
  • 56