a blog for those who code

Tuesday, 31 December 2019

Using Local References for Angular HTML Binding


Local Reference is an interesting concept in Angular where we can easily fetch a value of any input through local references. It also comes handy when we want to view or save the HTML element data where we can fetch the data from the component template and pass it to the component typescript class. Sometimes its also being called a Dynamic Template reference variable in Angular.


The way Local References works is that we need to create a reference variable by using the hash symbol(#) i.e. #localRef and it can be placed on any HTML element. The #localRef will hold the reference of that HTML element along with all the properties.

A question that always comes in the interview also is that What is Template Reference Variable in Angular. The answer is a template reference variable is referred to as a DOM element within a template i.e. same as a local reference.

Let's take an example. We have created an input element with a local reference as #myLocalRef and I am also going to pass the reference as a parameter to the javascript function as shown below:

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

To get the input field value through the local reference in the typescript file we will be using myLocalRef.value.

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
}

Now the above code is all about local references. Say for example you need to show some HTML content in a div, the best way of doing it is :

<div [innerHTML]="myHTMLString"></div>

The above code will show the HTML inside the div. There is another approach that you can use i.e. by using the ViewChild decorator. ViewChild decorator helps us to get the template elements injected in our TypeScript class i.e. in simple terms for accessing the local reference in our typescript file, we need ViewChild decorator as shown below:

@ViewChild('myLocalRef') myLocalRef;

Now let's say we have a div with local reference #myLocalRef and we need to add the HTML content to that div, which can be done as shown below :

@ViewChild('myLocalRef') myLocalRef: ElementRef;
getData(data) {
  this.myLocalRef.nativeElement.innerHTML = data;
}

Note: The value of the local reference in our class is not immediately available at the component constructor but at the ngAfterViewInit Life Cycle.

No comments:

Post a comment