Reputation: 3549
<form role="form" #form="form" (ng-submit)="submit(form.value)">
<input type="text" placeholder="Enter your name" ng-control="name">
<input type="text" placeholder="Enter your email" [(ng-model)]="email">
<button>Submit</button>
</form>
What is the diff b/w using ng-model and ng-control? When to use each of them?
Upvotes: 5
Views: 5018
Reputation: 41274
ngControl
, ngModel
and ngFormControl
are selectors for NgControlStatus
directive, so there's no difference between them...
NgControlStatus is Directive automatically applied to Angular forms that sets CSS classes based on control status (valid/invalid/dirty/etc).
NgFormControl
is directive that binds input field in the template to the Control
class that is used to programmatically create form fields.
NgFormControl Binds an existing Control to a DOM element.
Upvotes: 1
Reputation: 202206
Controls are responsible to get hints about the state of the form or a specific input (valid, pristine, touched, ...). It's commonly used to display validation errors if any. Here is a sample:
<div
[ngClass]="{'has-error':!inputControl.valid && !state.control.pending,'form-group':label,'form-group-sm':label}">
<label *ngIf="label" for="for"
class="col-sm-2 col-md-2 control-label">My input</label>
<div class="col-sm-8 col-md-8"
[ngClass]="{'col-sm-8': label, 'col-md-8': label}">
<input [(ngModel)]="myInput" [ngFormControl]="inputControl"/>
<span *ngIf="!inputControl.valid" class="help-block text-danger">
<div *ngIf="state?.errors?.required">The field is required</div>
(...)
<div *ngIf="state?.errors?.invalidZip">The zip code format isn't correct</div>
</span>
</div>
</div>
You can also detect changes on an input leveraging the valueChanges
attribute of control, as described below:
this.inputControl.valueChanges.subscribe(data => {
console.log('value updated - new value = '+data);
});
Since it's an observable you can leverage operators to create an aynchronous processing chain. For example to synchronize a list based on an input:
inputControl.valueChanges.debounceTime(500).flatMap(
val => {
return this.service.searchPlaces(val);
}).subscribe((data) => {
this.places = data;
});
On the other side, ngModel
allows to bound an input to a property of the component using two-way binding. If the property is updated by code, the input value will updated and if the input is updated by user, the property will be updated.
As pointed out by @Günter, your snippet contains some errors. Here is the correct one:
<form role="form" #form="form" (ngSubmit)="submit(form.value)">
<input type="text" placeholder="Enter your name" ngControl="name">
<input type="text" placeholder="Enter your email" [(ngModel)]="email">
<button>Submit</button>
</form>
Upvotes: 0