Using Local Variables within Angular, we can easily access and reference HTML elements and their properties within other HTML elements in the view. What does that mean? It means you can access value of text inputs or drop-down lists and even inner text properties of HTML elements easily within the view. This can help us to make dynamic changes in the View as other HTML element changes.

Demo Using Local Variables Within Angular

We define local variables within angular views in the following way:

<p #myPtag>I am a local variable</p>
And to use this local variable’s value, we can use Interpolation technique. We can get any attributes of this HTML element. So, if we want to access it’s text, we can do the following:


Here’s a more practical example where using local variable within angular views can be useful.
In this scenario, you want to track word count of an input field.

In your view, create a local variable for input tag.  Now, we can access it’s value in the paragraph easily as shown in the image below:

Demo Using Local Variable Within Angular
Demo Using Local Variable Within Angular

You should be able to see the length of characters being displayed within the <p> tag.

Note that we also have a “keyup” event attached within the <input> tag which allows to update the value of input text. If we didn’t have the “keyup” event, any update on the textbox wouldn’t be reflected as new value.

Using Value Of Local Variable In Functions

We can also make use of the value of local variables inside the app.component file.  Whenever we require them, we can simply pass the value as arguments to any function.

For example, we can create a button and send the value of local variable to a function through it’s click event like this:

<button (click)=demoFunction(charCounter)>Submit Value</button>
This will create a button which upon clicking calls the “demoFunction” as expected.