WillyC
WillyC

Reputation: 4705

What does a `#` attribute do in HTML?

I am writing a handler to do something to some element when a user clicks on a different element.

At first I had the following (This is using Angular2 but I suspect the only different is how the onclick event is handled):

        <span>
            <input type="text" id="bioName">
        </span>
        <span class="icon-pencil" (click)="editField(bioName);"></span>

...but this didn't work. I then found an example that identified the input field differently, and this did work for me. It was as follows:

        <span>
            <input type="text" #bioName>
        </span>
        <span class="icon-pencil" (click)="editField(bioName);"></span>

Unfortunately I can't find anything that explains this. Searching for "hash" and "pound" with HTML and Javascript yield too many results that have nothing to do with this in the subject area.

So what does # do in this case? Can id not be used to obtain a reference to the DOM element when setting up an event handler? What is this called so I can google it and read the appropriate documentation?

Upvotes: 15

Views: 3416

Answers (2)

Rok Povsic
Rok Povsic

Reputation: 4905

This is Angular2 specific, regular HTML doesn't recognize this syntax, i.e. you have to use id="bioName" in order to access the tag with CSS/JavaScript.

Here is more information on how to use # in Angular2.

Upvotes: 10

Stefan Svrkota
Stefan Svrkota

Reputation: 50623

Hash (#) is syntax for defining template variable in Angular 2 templates. It is used to assign unique identifiers to template elements which you can later use to get a reference to template elements in component. In your case, for example, you can use bioName variable to get a reference to input element in your component and you can do whatever you want with it there - get file name, file size or even file itself. This is done using ViewChild decorator. You can check out answer I wrote few days ago and see what template variables are mostly used for.

Upvotes: 5

Related Questions