a blog for those who code

Wednesday 6 February 2019

Working with Local References to get HTML Element in Angular

Local References in Angular comes handy when you just want to view and save the data of an HTML element from the template. Though there is two-way data binding which does the same, but we can also use Local References which can fetch directly from the component template and can be passed onto the component typescript class.

Local References can be placed on any HTML element. The reference will hold the reference of that element with all its properties and not only the value. references can be used everywhere in your template but not inside your typescript code. But if we are calling a method of a typescript file from a template then we can pass that local reference and that is the way we can pass the local reference to the typescript code.

You can declare a reference variable by using the hash symbol(#) like #myLocalRef on the element.

For Example :

  <input type="text" class="form-control" #myLocalRef />
  <button class="btn btn-primary" 
        (click)="onBtnClick(myLocalRef)">Click Me</button>

Now to retrieve the value of the input in the TypeScipt file we can use the below code

onBtnClick(myLocalRef: HTMLInputElement) {
  console.log(myLocalref); // Will show the HTML element with all its properties
  console.log(myLocalref.value); // Will show the value of the HTML input element

There is another way of getting access to the Local Reference or any element of the template directly from the typescript code using ViewChild decorator. Now the above method of passing the reference works great but what if you want to access the element before the method is being called.

  <input type="text" class="form-control" #myLocalRef />

For accessing the local reference we will pass the name of the local reference as a selector to the ViewChild decorator.

@ViewChild('myLocalRef') myLocalRef;

and use the myLocalRef to get the value of the element as shown below.


Do note that instead of using myLocalref.value we need to use myLocalRef.NativeElement.value to get the underlying element of the local reference and get the value of it.

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment