3

We create template input variable using let keyword while we create template reference variable using #var where var is the name of the variable. We can refer to a template reference variable anywhere in the template.

What about the scope of the template input variable? How does it differ from scope of template reference variable? Can someone help me to understand with examples?

<div *ngFor="let hero of heroes">{{hero.name}}</div> <!--hero is template input variable-->
<input #heroInput> {{heroInput.value}} <!--heroInput is template reference variable-->
3
  • is there anything unclear about my answer? Commented Aug 21, 2017 at 9:54
  • Thanks for your answer. Commented Aug 23, 2017 at 17:06
  • you are welcome, good luck Commented Aug 23, 2017 at 17:25

1 Answer 1

7

template context variable

When the compiler parses ng-template element contents it identifies let-tplVar="ctxValue" tokens and creates a binding:

[variable that can be used inside the template] = "context variable"
[tplVar]                                        = "ctxValue"

Context template variable can be used anywhere inside the template. So for ngFor:

<div *ngFor="let hero of heroes">{{hero.name}}</div>

the hero variable will be available inside the ng-template:

<ng-template ngFor [ngForOf]="heroes" let-hero="$implicit">
  <div>{{hero.name}}</div>

template variable

When compiler parses component template it creates binding for template variables and they can be accessed anywhere inside the template of the component:

<input #heroInput>
<span>{{heroInput.value}}</span>

You can also use template binding inside the ngFor:

<input #heroInput>
<div *ngFor="let hero of heroes">{{hero.name}} and {{heroInput.value}}</div>

Even though it is not provided in the template context by ngFor the compiler generates the following updateRenderer function:

  function(_ck,_v) {
      var currVal_0 = _v.context.$implicit.name;         <---- read from context
      var currVal_1 = jit_nodeValue4(_v.parent,4).value; <---- read from template variable
      _ck(_v,1,0,currVal_0,currVal_1);
  });
Sign up to request clarification or add additional context in comments.

1 Comment

what if inside the *ngFor you create more inputs with the same template variable #heroInput ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.