I have a query regarding the template variable in angular. Actually I was trying to access multiple elements with the help of the @ViewChildren() decorator. But when I was defining two element with the same template variable name like below example
then i was getting error below error
But when I wrapped both the elements with the div like below
then it started working fine and i was able to access both elements with @ViewChildren() decorator.
So I just wanted to know what is happening here? I mean whenever we want to use same template variable more than once do we need to always wrap them or what?
Can anyone explain what I am missing here?
Thanks
I tried googling but I did not get any proper reason for this behavior. So I just want to understand how template variable works.
this question is similar to this question Template parse errors: Reference "#XXX" is defined several times in angular but, they also did not provide any reason why it is working after wrapping inside the div.
Seems like a bug in earlier versions of Angular. This bug seems to be fixed for angular versions >12.0.0-next.0
I found the issues which contains some clarity as to why this error might be present and why it was removed.
Duplicate template reference variables are not treated as error with Ivy
fix(compiler): throw error for duplicate template references
This issue in replicable in angular 8 -> Stackblitz Demo
But not in angular 18 -> Stackblitz Demo
So JSmith answer is good for angular 8+, for latest versions of angular this error does not happen!