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>
<div> {{myPtag.innerText}} </div>
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:
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>