{"id":344,"date":"2020-09-22T14:19:22","date_gmt":"2020-09-22T12:19:22","guid":{"rendered":"http:\/\/www.myblog.nguenkam.com\/?p=344"},"modified":"2020-09-22T14:48:20","modified_gmt":"2020-09-22T12:48:20","slug":"working-with-angular-template-reference-variables","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2020\/09\/22\/working-with-angular-template-reference-variables\/","title":{"rendered":"Working with Angular Template Reference Variables"},"content":{"rendered":"\n<p>A&nbsp;<strong>template reference variable<\/strong>&nbsp;is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element,&nbsp;<a href=\"https:\/\/angular.io\/api\/core\/TemplateRef\">TemplateRef<\/a>, or a&nbsp;<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/Web_Components\">web component<\/a>.<\/p>\n\n\n\n<p>Use the hash symbol (#) to declare a reference variable. The following reference variable,&nbsp;<code>#phone<\/code>, declares a&nbsp;<code>phone<\/code>&nbsp;variable on an&nbsp;<code>&lt;input&gt;<\/code>&nbsp;element.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;input #phone placeholder=\"phone number\" \/>\n\n&lt;!-- lots of other elements -->\n\n&lt;!-- phone refers to the input element; pass its `value` to an event handler -->\n&lt;button (click)=\"callPhone(phone.value)\">Call&lt;\/button<\/code><\/pre>\n\n\n\n<p>We can refer to a template reference variable anywhere in the component&#8217;s template. Here, a&nbsp;<code>&lt;button&gt;<\/code>&nbsp;further down the template refers to the&nbsp;<code>phone<\/code>&nbsp;variable.<\/p>\n\n\n\n<p>Angular assigns each template reference variable a value based on where we declare the variable:<\/p>\n\n\n\n<ul><li>If we declare the variable on a component, the variable refers to the component instance.<\/li><li>If we declare the variable on a standard HTML tag, the variable refers to the element.<\/li><li>If we declare the variable on an&nbsp;<code>&lt;ng-template&gt;<\/code>&nbsp;element, the variable refers to a&nbsp;<code><a href=\"https:\/\/angular.io\/api\/core\/TemplateRef\">TemplateRef<\/a><\/code>&nbsp;instance, which represents the template.<\/li><li>If the variable specifies a name on the right-hand side, such as&nbsp;<code>#var=\"<a href=\"https:\/\/angular.io\/api\/forms\/NgModel\">ngModel<\/a>\"<\/code>, the variable refers to the directive or component on the element with a matching&nbsp;<code>exportAs<\/code>&nbsp;name<\/li><\/ul>\n\n\n\n<h4>How a reference variable gets its value<\/h4>\n\n\n\n<p>In most cases, Angular sets the reference variable&#8217;s value to the element on which it is declared. In the previous example,&nbsp;<code>phone<\/code>&nbsp;refers to the phone number&nbsp;<code>&lt;input&gt;<\/code>. The button&#8217;s click handler passes the&nbsp;<code>&lt;input&gt;<\/code>&nbsp;value to the component&#8217;s&nbsp;<code>callPhone()<\/code>&nbsp;method.<\/p>\n\n\n\n<p>The&nbsp;<code><a href=\"https:\/\/angular.io\/api\/forms\/NgForm\">NgForm<\/a><\/code>&nbsp;directive can change that behavior and set the value to something else. In the following example, the template reference variable,&nbsp;<code>itemForm<\/code>, appears three times separated by HTML.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;form #itemForm=\"ngForm\" (ngSubmit)=\"onSubmit(itemForm)\">\n  &lt;label for=\"name\"\n    >Name &lt;input class=\"form-control\" name=\"name\" ngModel required \/>\n  &lt;\/label>\n  &lt;button type=\"submit\">Submit&lt;\/button>\n&lt;\/form>\n\n&lt;div &#91;hidden]=\"!itemForm.form.valid\">\n  &lt;p>{{ submitMessage }}&lt;\/p>\n&lt;\/div><\/code><\/pre>\n\n\n\n<p>The reference value of&nbsp;<code>itemForm<\/code>, without the&nbsp;<code><a href=\"https:\/\/angular.io\/api\/forms\/NgForm\">ngForm<\/a><\/code>&nbsp;attribute value, would be the&nbsp;<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/HTMLFormElement\">HTMLFormElement<\/a>. There is, however, a difference between a&nbsp;<code><a href=\"https:\/\/angular.io\/api\/core\/Component\">Component<\/a><\/code>&nbsp;and a&nbsp;<code><a href=\"https:\/\/angular.io\/api\/core\/Directive\">Directive<\/a><\/code>&nbsp;in that a&nbsp;<code><a href=\"https:\/\/angular.io\/api\/core\/Component\">Component<\/a><\/code>&nbsp;will be referenced without specifying the attribute value, and a&nbsp;<code><a href=\"https:\/\/angular.io\/api\/core\/Directive\">Directive<\/a><\/code>&nbsp;will not change the implicit reference (that is, the element).<\/p>\n\n\n\n<p>However, with&nbsp;<code><a href=\"https:\/\/angular.io\/api\/forms\/NgForm\">NgForm<\/a><\/code>,&nbsp;<code>itemForm<\/code>&nbsp;is a reference to the&nbsp;<a href=\"https:\/\/angular.io\/api\/forms\/NgForm\">NgForm<\/a>&nbsp;directive with the ability to track the value and validity of every control in the form.<\/p>\n\n\n\n<p>The native&nbsp;<code>&lt;form&gt;<\/code>&nbsp;element doesn&#8217;t have a&nbsp;<code>form<\/code>&nbsp;property, but the&nbsp;<code><a href=\"https:\/\/angular.io\/api\/forms\/NgForm\">NgForm<\/a><\/code>&nbsp;directive does, which allows disabling the submit button if the&nbsp;<code>itemForm.form.valid<\/code>&nbsp;is invalid and passing the entire form control tree to the parent component&#8217;s&nbsp;<code>onSubmit()<\/code>&nbsp;method.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>The scope of a reference variable is the entire template. So, don&#8217;t define the same variable name more than once in the same template as the runtime value will be unpredictable.<\/p><\/blockquote>\n\n\n\n<p>Well! We cannot access the template reference variable inside the component class or typescript logic but still, we can use that variable by passing it through a method which will be called by the event listener.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;div>\r\n&lt;label for=\"Name\">Name&lt;\/label>\r\n&lt;input type=\"text\" #nameInput>\r\n&lt;button (click)=\"onSaveName(nameInput)\">Save Name&lt;\/button>\r\n&lt;\/div><\/code><\/pre>\n\n\n\n<p>Passing that local variable with omitting # symbol.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import {\r\n  Component,\r\n} from '@angular\/core';\r\n@Component({\r\n  selector: 'my-app',\r\n  templateUrl: '.\/app.component.html',\r\n  styleUrls: &#91;'.\/app.component.css']\r\n})\r\nexport class AppComponent {\r\n  constructor() {}\r\n  onSaveName(name: HTMLInputElement) {\r\n    console.log(( &lt; HTMLInputElement > name).value);\r\n  }\r\n}<\/code><\/pre>\n\n\n\n<p>Here, we are expecting a name parameter which will be of type\u00a0<strong>HTMLInputElement<\/strong>\u00a0and also inside the body of the method, we have wrapped the name variable with the same type. It is because we are accessing the instance of the element which is\u00a0<strong>&lt;input><\/strong>\u00a0type.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"http:\/\/www.writesomecode.in\/Angular\/media\/19\/LocalRef_HTMLInputElement.gif\" alt=\"insert\" width=\"300\" height=\"219\"\/><\/figure>\n\n\n\n<p>We can see in the above screenshot that all the generic properties of Input element are wrapped under HTMLInputElement. It is one of good practice to explicitly define the parameter type we are about to receive in the method to avoid further confusion with variable types in the method body. If we do so, Editor intellisense will show us all the methods and properties can be called on the received parameter property.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"http:\/\/www.writesomecode.in\/Angular\/media\/19\/editor_intellisense.gif\" alt=\"insert\" width=\"496\" height=\"276\"\/><\/figure>\n\n\n\n<h4>@ViewChild()<\/h4>\n\n\n\n<p>There is one more way to accessing the template reference variable is using\u00a0<strong>@ViewChild()<\/strong>\u00a0decorator, using this decorator, we can reference that variable inside our component without passing it via method as a parameter, or we can say, if we need to access it before the\u00a0<strong>onSaveName()<\/strong>\u00a0method get executed.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import {\r\n  Component,\r\n  OnInit,\r\n  ViewChild,\r\n  ElementRef,\r\n  AfterViewChecked\r\n} from '@angular\/core';\r\n@Component({\r\n  selector: 'my-app',\r\n  templateUrl: '.\/app.component.html',\r\n  styleUrls: &#91;'.\/app.component.css']\r\n})\r\nexport class AppComponent implements OnInit, AfterViewChecked {\r\n  @ViewChild('nameInput') inputNameRef: ElementRef;\r\n  constructor() {}\r\n  ngOnInit() {}\r\n  onSaveName(name: HTMLInputElement) {\r\n    console.log(( &lt; HTMLInputElement > name).value);\r\n    console.log(this.inputNameRef.nativeElement.value);\r\n  }\r\n  ngAfterViewChecked() {\r\n    console.log(\"After view got Checked\");\r\n    console.log(this.inputNameRef.nativeElement.value);\r\n  }\r\n}<\/code><\/pre>\n\n\n\n<p>Here, the output will be logged 3 times on the control, two for the method and one after AfterViewChecked lifecycle hook. Don\u2019t forget that with the\u00a0<strong>@ViewChild()<\/strong>\u00a0decorator, our reference to the variable will be\u00a0<strong>ElementRef\u00a0<\/strong>type Since we are trying to access a reference to an element of our template view.\u00a0<strong>ElementRef\u00a0<\/strong>has sub-property called\u00a0<strong>nativeElement<\/strong>\u00a0which wraps all the underlying properties of that specific referenced element.<\/p>\n\n\n\n<h4>Alternative syntax<\/h4>\n\n\n\n<p>We can use the&nbsp;<code>ref-<\/code>&nbsp;prefix alternative to&nbsp;<code>#<\/code>. This example declares the&nbsp;<code>fax<\/code>&nbsp;variable as&nbsp;<code>ref-fax<\/code>&nbsp;instead of&nbsp;<code>#fax<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;input ref-fax placeholder=\"fax number\" \/>\n&lt;button (click)=\"callFax(fax.value)\">Fax&lt;\/button><\/code><\/pre>\n\n\n\n<h5>Reference:<\/h5>\n\n\n\n<p><a href=\"https:\/\/angular.io\/\">https:\/\/angular.io\/<\/a> <\/p>\n\n\n\n<p><a href=\"http:\/\/www.writesomecode.in\/\">http:\/\/www.writesomecode.in\/<\/a><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A&nbsp;template reference variable&nbsp;is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element,&nbsp;TemplateRef, or a&nbsp;web component. Use the hash symbol (#) to declare a reference variable. The following reference variable,&nbsp;#phone, declares a&nbsp;phone&nbsp;variable on an&nbsp;&lt;input&gt;&nbsp;element. We can refer to a template reference variable [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":346,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37],"tags":[110,40,65,67,66],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/344"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=344"}],"version-history":[{"count":8,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/344\/revisions"}],"predecessor-version":[{"id":466,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/344\/revisions\/466"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/346"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=344"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=344"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=344"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}