Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 439
Alexander Tarasenko Avatar asked Jul 23 '18 15:07

Alexander Tarasenko


People also ask

What is Angular reference template?

Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component. Template Reference Variable can refer to the following – DOM element. Directives.

What is local reference in Angular?

Instead of two-way binding, we can easily fetch a value of any input through local references in Angular. Local references can be fetched directly from the component template and into the component typescript class. Lets check out how do we use local references.

What is variable$ in Angular?

Angular assigns a template variable a value based on where you declare the variable: If you declare the variable on a component, the variable refers to the component instance. If you declare the variable on a standard HTML tag, the variable refers to the element.

How do I get ng template reference in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .


1 Answers

You don't have to use [(ngModel)], ever.NgModel is a part of the Angular FormsModule. If you have the FormsModule imported, you can use the extra functionality of ngModel. Doing so creates an NgForm and FormControl that you can use in more complicated reactive and dynamic forms and will track the field's status, e.g. dirty, touched. It will also allow you to place error validators on the field, as well as expose an Observable stream of value changes.

Using template variables and ViewChild to just grab an input element and interact with it as you would with vanilla JS is just fine as well, especially if your use case is something simple. This way you could avoid including the FormsModule in your module.

like image 177
joh04667 Avatar answered Oct 07 '22 12:10

joh04667