NgModel • Angular
Using ngModel on a standalone control
The following examples show a simple standalone control using ngModel:
import {Component} from '@angular/core';
@Component({
selector: 'example-app',
template: `
<input [(ngModel)]="name" #ctrl="ngModel" required />
<p>Value: {{ name }}</p>
<p>Valid: {{ ctrl.valid }}</p>
<button (click)="setValue()">Set value</button>
`,
standalone: false,
})
export class SimpleNgModelComp {
name: string = '';
setValue() {
this.name = 'Nancy';
}
}
When using the ngModel within <form> tags, you'll also need to supply a name attribute
so that the control can be registered with the parent form under that name.
In the context of a parent form, it's often unnecessary to include one-way or two-way binding,
as the parent form syncs the value for you. You access its properties by exporting it into a
local template variable using ngForm such as (#f="ngForm"). Use the variable where
needed on form submission.
If you do need to populate initial values into your form, using a one-way binding for
ngModel tends to be sufficient as long as you use the exported form's value rather
than the domain model's value on submit.
Using ngModel within a form
The following example shows controls using ngModel within a form:
import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<input name="first" ngModel required #first="ngModel" />
<input name="last" ngModel />
<button>Submit</button>
</form>
<p>First name value: {{ first.value }}</p>
<p>First name valid: {{ first.valid }}</p>
<p>Form value: {{ f.value | json }}</p>
<p>Form valid: {{ f.valid }}</p>
`,
standalone: false,
})
export class SimpleFormComp {
onSubmit(f: NgForm) {
console.log(f.value); // { first: '', last: '' }
console.log(f.valid); // false
}
}
Using a standalone ngModel within a group
The following example shows you how to use a standalone ngModel control within a form. This controls the display of the form, but doesn't contain form data.
<form>
<input name="login" ngModel placeholder="Login">
<input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
</form>
<!-- form value: {login: ''} -->
Setting the ngModel name attribute through options
The following example shows you an alternate way to set the name attribute. Here,
an attribute identified as name is used within a custom form control component. To still be able
to specify the NgModel's name, you must specify it using the ngModelOptions input instead.
<form>
<my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
</my-custom-form-control>
</form>
<!-- form value: {user: ''} -->