217

I am working with angular 2 and I have found something like

<input #searchBox (keyup)="search(searchBox.value)"

and it works.

However, I don't understand the meaning of #searchBox. I haven't found anything clear neither in the doc.

Could anyone explain to me how it works?

2

4 Answers 4

257

It's syntax used in the Angular 2 templating system which declares DOM elements as variables.

Here I give my component a template URL:

import {Component} from 'angular2/core';

@Component({
   selector: 'harrys-app',
   templateUrl: 'components/harry/helloworld.component.html'
})

export class HarrysApp {}

Templates render HTML. In a template you can use data, property binding and event binding. This is accomplished with the following syntax:

# - variable declaration

() - event binding

[] - property binding

[()] - two-way property binding

{{ }} - interpolation

* - structural directives

The # syntax can declare local variable names which references DOM objects in a template. e.g.

 <span [hidden]="harry.value">*</span>
 <input type="text" #harry>
 {{ harry.value }}
5
  • 13
    Working example: <input #bla style="display: none;" value="Foo" /<div> {{bla.value}} </div>. Foo is displayed in div.
    – broadband
    Commented Mar 12, 2018 at 12:16
  • 4
    And there is no way for that variable declaration itself to be a variable? I am trying to create material menu items from a complex nested object of menus and this has stymied me. I can't seem to dynamically create the dom variables. Do they really need to be hard-coded in the dom? Commented Apr 27, 2018 at 0:42
  • 4
    Official Document Reference: angular.io/guide/…
    – 千木郷
    Commented Nov 29, 2018 at 15:01
  • Can one element have more than one hashtag variable declarations? Commented Aug 13, 2020 at 21:26
  • Two-way property binding syntax [()] can be easily remembered by the catchphrase "banana in a box".
    – aleksejjj
    Commented May 12, 2022 at 22:34
82

When you set this #searchBox, you can get this input on your Typescript like

    @ViewChild('searchBox') searchBox;
    console.info(searchBox.nativeElement.value)

EDIT

Adding some example: https://plnkr.co/edit/w2FVfKlWP72pzXIsfsCU?p=preview

0
43

From angulartraining.com:

Template reference variables are a little gem that allows to get a lot of nice things done with Angular. I usually call that feature “the hashtag syntax” because, well, it relies on a simple hashtag to create a reference to an element in a template:

<input #phone placeholder="phone number">

What the above syntax does is fairly simple: It creates a reference to the input element that can be used later on in my template. Note that the scope for this variable is the entire HTML template in which the reference is defined.

Here’s how I could use that reference to get the value of the input, for instance:

<!-- phone refers to the input element --> 
<button (click)="callPhone(phone.value)">Call</button>

Note that phone refers to the HTMLElement object instance for the input. As a result, phone has all of the properties and methods of any HTMLElement (id, name, innerHTML, value, etc.)

The above is a nice way to avoid using ngModel or some other kind of data binding in a simple form that does not require much in terms of validation.


Does this also work with components?

The answer is YES!

... the best part of it is that we’re getting a reference to the actual component instance, HelloWorldComponent, so we can access any methods or properties of that component (even if they are declared as private or protected, which is surprising):

@Component({
  selector: 'app-hello',
  // ...

export class HelloComponent {
   name = 'Angular';
}

[...]

<app-hello #helloComp></app-hello>

<!-- The following expression displays "Angular" -->
{{helloComp.name}}
1
  • 2
    "even if they are declared as private or protected, which is surprising" - keep in mind that access specifiers are a compile time guard, and typically don't do anything after the code is compiled and running.
    – Tongfa
    Commented May 23, 2019 at 15:21
28

It creates a template variable that references

  • the input element if the element is a plain DOM element
  • the component or directive instance if it is an element with a component or directive
  • some specific component or directive if it's used like #foo="bar" when bar is
@Directive({ // or @Component
  ...
  exportAs: 'bar'
})

Such a template variable can be referenced in template bindings or in element queries like

@ViewChild('searchBox') searchBox:HTMLInputElement;
4
  • This is amazing. By the way - it's pretty similar to the ngModel, isn't it?
    – kind user
    Commented Mar 8, 2017 at 17:17
  • Not really. ngModel is for forms integration. You can do all other kinds of bindings without ngModel. Commented Mar 8, 2017 at 17:22
  • Last thing, how did you use ngAfterViewInit without actually importing it? And implementing? It's a build in feature on plunker?
    – kind user
    Commented Mar 8, 2017 at 17:26
  • No, Angular doesn't depend on the lifecycle interfaces be declared explicitely. If the method exists it gets called. Implementing the interfaces explicitely is good practice though. Commented Mar 8, 2017 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.