NgModel

根据领域对象创建一个 FormControl 实例,并把它绑定到一个表单控件元素上。

Creates a FormControl instance from a domain model and binds it to a form control element.

查看"说明"...

参见

NgModule

选择器

  • [ngModel]:not([formControlName]):not([formControl])

属性

属性说明
control: FormControl 只读
viewModel: any

Internal reference to the view model value.

@Input()
name: string

Tracks the name bound to the directive. The parent form uses this name as a key to retrieve this control's value.

@Input('disabled')
isDisabled: boolean

Tracks whether the control is disabled.

@Input('ngModel')
model: any

Tracks the value bound to this directive.

@Input('ngModelOptions')
options: { name?: string; standalone?: boolean; updateOn?: FormHooks; }

跟踪该 ngModel 实例的配置项。

Tracks the configuration options for this ngModel instance.

name:用来设置表单控件元素的 name 属性的另一种方式。参见把 ngModel 用作独立控件的那个例子

name: An alternative to setting the name attribute on the form control element. See the example for using NgModel as a standalone control.

standalone:如果为 true,则此 ngModel 不会把自己注册进它的父表单中,其行为就像没在表单中一样。默认为 false。

standalone: When set to true, the ngModel will not register itself with its parent form, and acts as if it's not in the form. Defaults to false.

updateOn: 用来定义该何时更新表单控件的值和有效性。默认为 'change'。可能的取值为:'change' | 'blur' | 'submit'

updateOn: Defines the event upon which the form control value and validity update. Defaults to 'change'. Possible values: 'change' | 'blur' | 'submit'.

@Output('ngModelChange')
update: EventEmitter

Event emitter for producing the ngModelChange event after the view model updates.

path: string[] 只读

Returns an array that represents the path from the top-level form to this control. Each index is the string name of the control on that level.

formDirective: any 只读

The top-level directive for this control if present, otherwise null.

validator: ValidatorFn | null 只读

Synchronous validator function composed of all the synchronous validators registered with this directive.

asyncValidator: AsyncValidatorFn | null 只读

Async validator function composed of all the async validators registered with this directive.

继承自 NgControl

继承自 AbstractControlDirective

模板变量参考手册

标识符用途
ngModel#myTemplateVar="ngModel"

说明

这个 FormControl 实例将会跟踪值、用户交互和控件的验证状态,以保持视图与模型的同步。 如果用在某个父表单中,该指令还会把自己注册为这个父表单的子控件。

The FormControl instance tracks the value, user interaction, and validation status of the control and keeps the view synced with the model. If used within a parent form, the directive also registers itself with the form as a child control.

这个指令可以单独使用,也可以用作一个大表单的一部分。你所要做的一切就是用 ngModel 选择器来激活它。

This directive is used by itself or as part of a larger form. Use the ngModel selector to activate it.

它可以接受一个领域模型作为可选的 Input。如果使用 [] 语法来单向绑定到 ngModel,那么在组件类中修改领域模型将会更新视图中的值。 如果使用 [()] 语法来双向绑定到 ngModel,那么视图中值的变化会随时同步回组件类中的领域模型。

It accepts a domain model as an optional Input. If you have a one-way binding to ngModel with [] syntax, changing the value of the domain model in the component class sets the value in the view. If you have a two-way binding with [()] syntax (also known as 'banana-box syntax'), the value in the UI always syncs back to the domain model in your class.

如果你希望查看与 FormControl 相关的属性(比如校验状态),你也可以使用 ngModel 作为键,把该指令导出到一个局部模板变量中(如:#myVar="ngModel")。 你也可以使用该指令的 control 属性来访问此控件,实际上你要用到的大多数属性(如 validdirty)都会委托给该控件,这样你就可以直接访问这些属性了。 你可以在 AbstractControlDirective 中直接查看这些属性的完整列表。

To inspect the properties of the associated FormControl (like validity state), export the directive into a local template variable using ngModel as the key (ex: #myVar="ngModel"). You then access the control using the directive's control property, but most properties used (like valid and dirty) fall through to the control anyway for direct access. See a full list of properties directly available in AbstractControlDirective.

在独立控件模式下使用 ngModel

Using ngModel on a standalone control

如果你希望查看与 FormControl 相关的属性(比如校验状态),你也可以使用 ngModel 作为键,把该指令导出到一个局部模板变量中(如:#myVar="ngModel")。 你也可以使用该指令的 control 属性来访问此控件,实际上你要用到的大多数属性(如 validdirty)都会委托给该控件,这样你就可以直接访问这些属性了。 你可以在 AbstractControlDirective 中直接查看这些属性的完整列表。

下面是一个在简单的独立控件中使用 ngModel 的例子:

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> `, }) export class SimpleNgModelComp { name: string = ''; setValue() { this.name = 'Nancy'; } }
      
      
  1. import {Component} from '@angular/core';
  2.  
  3. @Component({
  4. selector: 'example-app',
  5. template: `
  6. <input [(ngModel)]="name" #ctrl="ngModel" required>
  7.  
  8. <p>Value: {{ name }}</p>
  9. <p>Valid: {{ ctrl.valid }}</p>
  10. <button (click)="setValue()">Set value</button>
  11. `,
  12. })
  13. export class SimpleNgModelComp {
  14. name: string = '';
  15.  
  16. setValue() { this.name = 'Nancy'; }
  17. }

当在 <form> 标签中使用 ngModel 时,你还需要提供一个 name 属性,以便该控件可以使用这个名字把自己注册到父表单中。

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.

在父表单的上下文中,通常不用包含单向或双向绑定,因为这个父表单将会为你同步该值。 你可以使用 ngForm 把它导出给一个模板局部变量(如 #f="ngForm"),以访问它的属性。 可以在任何需要提交表单的地方使用它。

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.

如果你只是要为表单设置初始值,对 ngModel 使用单向绑定就够了。在提交时,你可以使用从表单导出的值,而不必使用领域模型的值。

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.

在表单中使用 ngModel

Using ngModel within a form

下面的例子展示了如何在表单中使用 ngModel

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> `, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } }
      
      
  1. import {Component} from '@angular/core';
  2. import {NgForm} from '@angular/forms';
  3.  
  4. @Component({
  5. selector: 'example-app',
  6. template: `
  7. <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
  8. <input name="first" ngModel required #first="ngModel">
  9. <input name="last" ngModel>
  10. <button>Submit</button>
  11. </form>
  12. <p>First name value: {{ first.value }}</p>
  13. <p>First name valid: {{ first.valid }}</p>
  14. <p>Form value: {{ f.value | json }}</p>
  15. <p>Form valid: {{ f.valid }}</p>
  16. `,
  17. })
  18. export class SimpleFormComp {
  19. onSubmit(f: NgForm) {
  20. console.log(f.value); // { first: '', last: '' }
  21. console.log(f.valid); // false
  22. }
  23. }

在表单组中使用独立 ngModel

Using a standalone ngModel within a group

下面的例子演示了如何在表单中使用独立 ngModel 控件。它控制表单的显示,但并不包含表单数据。

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: ''} -->
      
      <form>
  <input name="login" ngModel placeholder="Login">
  <input type="checkbox" ngModel [ngModelOptions]="{standalone: true}"> Show more options?
</form>
<!-- form value: {login: ''} -->
    

通过选项设置 ngModel 的 name 属性

Setting the ngModel name attribute through options

下面的例子展示了设置 name 属性的另一种方式。该 name 属性要和自定义表单组件一起使用,而该自定义组件的 @Input 属性 name 已用作其它用途。

The following example shows you an alternate way to set the name attribute. The name attribute is used within a custom form component, and the name @Input property serves a different purpose.

<form> <my-person-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}"> </my-person-control> </form> <!-- form value: {user: ''} -->
      
      <form>
  <my-person-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
  </my-person-control>
</form>
<!-- form value: {user: ''} -->
    

方法

A lifecycle method called when the directive's inputs change. For internal use only.

ngOnChanges(changes: SimpleChanges)
      
      ngOnChanges(changes: SimpleChanges)
    
参数
changes SimpleChanges

A object of key/value pairs for the set of changed inputs.

Lifecycle method called before the directive's instance is destroyed. For internal use only.

ngOnDestroy(): void
      
      ngOnDestroy(): void
    
参数

没有参数。

返回值

void

Sets the new value for the view model and emits an ngModelChange event.

viewToModelUpdate(newValue: any): void
      
      viewToModelUpdate(newValue: any): void
    
参数
newValue any

The new value emitted by ngModelChange.

返回值

void

继承自 NgControl

继承自 AbstractControlDirective