Local References in Angular

Local references are a nice feature for communication between components and the templates. They can be placed on any HTML element by typing a hashtag with a name of your choice on the HTML element. 

The local reference will hold a reference to the whole HTML element with all its properties and you can use them directly only on the template.

We can use the local reference in the component by passing it through a function in the template and then we can use it in the component code. 


import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  onButtonClick(inputElement:HTMLInputElement) {
    console.log(inputElement);
    console.log(inputElement.value);
  }
}


<div>
 <input type="text" value="someValue" #textInput/>
 <br/>
 <button (click)="onButtonClick(textInput)">Click Me</button>
</div>

So with the local reference we  can get access to elements in our templates and then use them directly in the template or to pass them with a function and use them in the component code.

there is another way of getting access to local references or to any element directly from within the component code. in the example above we are passing the reference when we call a method but sometimes we want to get access before we call the method and for that we can use the @ViewChild decorator to fetch the local reference.


import { Component, ElementRef, OnInit, ViewChild } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  @ViewChild("textInput2", { static: true }) anotherTextInput: ElementRef;

  ngOnInit() {
    console.log(this.anotherTextInput.nativeElement.value);
  }
}


<div>
  <input type="text" value="anotherValue" #textInput2/>
</div>

keep in mind that we should not change the element (properties of the element) with the viewChild, this is not the way to access the DOM, angular offers us a better way to do this with directives.

we are using the “static: true” since we access the selected element in ngOnInit lifecycle hook. if we don’t access it in the ngOnInit, we don’t need to set static (for angular8 and below we should set the static to false).

Click here for live demo