Return to site

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

· ngInterview,fullstack

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.

 

𝐒𝐨, 𝐀𝐧𝐠𝐮𝐥𝐚𝐫 𝐚𝐥𝐥𝐨𝐰𝐬 𝐭𝐨 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐚 𝐃𝐎𝐌 𝐞𝐥𝐞𝐦𝐞𝐧𝐭 𝐝𝐢𝐫𝐞𝐜𝐭𝐥𝐲 𝐟𝐫𝐨𝐦 𝐚 𝐭𝐞𝐦𝐩𝐥𝐚𝐭𝐞, 𝐭𝐡𝐚𝐧𝐤𝐬 𝐭𝐨 𝐭𝐞𝐦𝐩𝐥𝐚𝐭𝐞 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞.