0

I'm trying to be able to reassign a templateRefVar available in an Angular Template. I'm able to use the 'as' keyword to give it an assignment for the element it's in as can be seen in the example below:

<input value="hello" #templateRefVar>

<!-- This works! -->
<div *ngIf="templateRefVar.value as value">
  I can output {{ value }}
</div>

I however am having difficulty to get it to work using the && operator if I extend the *ngIf as it will throw an error:

<!-- I can't get it to work using && -->
<div *ngIf="(templateRefVar.value as value) === 'hello' && templateRefVar.value">
  I cannot output {{ value }} and get an error.
</div>

I'm actually looking for a way to reassign the value without the need of *ngIf directive. I'm hoping there is a standard api I don't know about that can let me reassign template variables on the fly like below example (with wishful thinking..)

<!-- Wish this worked : ( -->
<div *ngIf="templateRefVar.value === 'hello'" #reassignment="templateRefVar.value as value">
 Hoping I can output {{ value }}
</div>

Update to comments:

It's for convenience if I need to do validation like in forms:

<!-- check if password.errors is not null before attempting to show validation messages regarding password.errors -->
<ng-container *ngIf="!verifyPassword.pristine && password.errors as errors"
   <!-- Using errors as shorter syntax rather than password.errors on different validation checks below -->
   <div>
     {{ errors.minlength }}
   </div>
   <div>
     {{ errors.nextError }}
   </div>
   <div>
     {{ errors.someOtherValidationMessage }}
   </div>
</ng-container>

Which is why I'm hoping Angular has an api that supports a templateRefVar reassignment in case I have a longer *ngIf that is more complex than the above.

Jonathan002
  • 9,639
  • 8
  • 37
  • 58
  • What error do you get? – user184994 Apr 28 '18 at 13:36
  • I'm getting the error "Parser Error: Missing expected ) at column 61 in [((templateRefVar.value === 'hello') && templateRefVar.value as value)] in ng:///AppCoreModule/LoginComponent.html@91:5 ("": – Jonathan002 Apr 28 '18 at 13:42
  • i can't wrap my head around the idea behind reassigning to another variable... – Joseph Wu Apr 28 '18 at 14:19
  • What do you want to achieve by writing (templateRefVar.value as value) === 'hello' && templateRefVar.value"? What is the additional '&& templateRefVar.value' for? –  Apr 28 '18 at 14:23
  • You're confusing template reference variables with local variables. Possible duplicate of [Not understanding use of template variables in \*ngIf statement](https://stackoverflow.com/questions/48965277/not-understanding-use-of-template-variables-in-ngif-statement) – Estus Flask Apr 28 '18 at 17:05
  • use two *ngIf, one to assig a local variable, another one to make visible or not. tip: you can use ng-container if you don't want create an extra div – Eliseo Apr 28 '18 at 18:49
  • @Eliseo thanks for the advice! :) – Jonathan002 Apr 30 '18 at 06:19

0 Answers0