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)
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With