Search code examples
angularangular-ngmodelangular-template-variable

Angular reference # vs ngModel


I wonder when do I have to use [(ngModel)] on my input and when I can just use #reference For example

<div class="form-group">
  <div class="input-group mb-2">
    <input type="text" class="form-control" [(ngModel)]="newUser">
    <button class="btn btn-outline-success" (click)="onAddUser()">Add user</button>
  </div>
</div>

Should I do it this way here, or maybe I can do it this way instead:

<div class="form-group">
  <div class="input-group mb-2">
    <input type="text" class="form-control" #newUser>
    <button class="btn btn-outline-success" (click)="onAddUser(newUser.value)">
      Add user
    </button>
  </div>
</div>

I would be thankful for any answers)


Solution

  • From Documentation:

    • [(ngModel)] allow you to bind a template element's value to a component variable.
    • # : can be referred anywhere in the template

    In summary, ngModel refers to the value of a variable, while the # reference refers to a template object (HTML Element). However, you can still access a template reference variable using ViewChild.

    I think the examples you wrote are both correct. I would prefer using ngModel if I need the value in my component, and # if I need it in the DOM.