Return to site

ANGULAR INTERVIEW QUESTION: What is a template variable in Angular?

December 4, 2021

A template variable is a reference to a DOM element, that we can directly declare from the template.

 

We use the sharp symbol ย "#" to declare a template variable.

 

In app.component.html:

 

๐Ÿ‘‰Here we declare a variable '๐ง๐š๐ฆ๐ž' that targets the '๐ข๐ง๐ฉ๐ฎ๐ญ' DOM element, since it is declared in that tag.

That way the '๐ง๐š๐ฆ๐ž' variable references the '๐ข๐ง๐ฉ๐ฎ๐ญ' ย DOM element.

That's a template variable.

 

 

๐๐ฎ๐ญ ๐ฐ๐ก๐š๐ญ ๐ข๐ฌ ๐ข๐ญ๐ฌ ๐ซ๐จ๐ฅ๐ž?

First, it allows to access the value of the element input elsewhere in your template by using this '๐ง๐š๐ฆ๐ž' variable:

๐Ÿ’กYou can use this variable wherever you want in that component template html. But you can't use it in another template html file.

 

๐’๐จ, ๐€๐ง๐ ๐ฎ๐ฅ๐š๐ซ ๐š๐ฅ๐ฅ๐จ๐ฐ๐ฌ ๐ญ๐จ ๐ซ๐ž๐Ÿ๐ž๐ซ๐ž๐ง๐œ๐ž ๐š ๐ƒ๐Ž๐Œ ๐ž๐ฅ๐ž๐ฆ๐ž๐ง๐ญ ๐๐ข๐ซ๐ž๐œ๐ญ๐ฅ๐ฒ ๐Ÿ๐ซ๐จ๐ฆ ๐š ๐ญ๐ž๐ฆ๐ฉ๐ฅ๐š๐ญ๐ž, ๐ญ๐ก๐š๐ง๐ค๐ฌ ๐ญ๐จ ๐ญ๐ž๐ฆ๐ฉ๐ฅ๐š๐ญ๐ž ๐ฏ๐š๐ซ๐ข๐š๐›๐ฅ๐ž.