*ngIf and local template variables

We can reference a local template variable on the same element, on a sibling element, or on any child elements. — ref

*ngIf becomes/expands to

<template [ngIf]="_model">
    <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
     ngControl="test1" #myInput>
</template>

So local template variable #myInput can only be referenced inside the template block (i.e., sibling and/or child elements). Hence you would have to put any HTML that wants to reference the local template variable inside the template:

<template [ngIf]="_model">
   <input type="text" class="form-control" required [(ngModel)]="_model.firstName"
    ngControl="test1"  #myInput >
   <br>Class (this works): {{myInput?.className}}
</template>

Plunker


If you need to show something outside the template block related to the input, use @ViewChildren('myInput') list:QueryList<ElementRef> and then subscribe to changes:

ngAfterViewInit() {
   this.list.changes.subscribe( newList =>
      console.log('new list size:', newList.length)
   )
}

See more QueryList methods in the API doc.

Leave a Comment