What's the difference between using id="mydiv" and #mydiv in Angular HTML?

If you want to identify an element using javascript function or from your controller using getElementByID or to point to a style in a style sheet, you need to set the id that has to that element be unique throughout your DOM.

However, when you want to access your element within the DOM file you need to refer the element using #. if you use just id you will have the error Cannot read property 'XXX' of undefined in your browser.

For example, in order to show/hide a button using the value of an input in DOM file without writing any javascript/angular code you could do something like the following, in which setting the id wouldn't work out.

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input #nameField matInput placeholder="Name">
  </mat-form-field>

  <button type="button" *ngIf="nameField.value!==''" >Submit</button>
</form>

Reference to this to dealing with user input and this as a broader explanation of the # tag.

Tags:

Html

Angular