填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

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唯讀
@Input()
name: string

追蹤繫結到指令的名稱。如果存在父表單,它將使用此名稱作為鍵名來檢索此控制元件的值。

Tracks the name bound to the directive. If a parent form exists, it 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. If no parent form exists, this option has no effect.

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

更新檢視模型後,ngModelChange 的事件發射器。

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唯讀

此控制元件的最上層指令(如果存在),否則為 null。

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

繼承自 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 domain model's value in the component class sets the value in the view. If you have a two-way binding with [()] syntax (also known as 'banana-in-a-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 thevalidity state), export the directive into a local template variable using ngModel as the key (ex: #myVar="ngModel"). You can then access the control using the directive's control property. However, the most commonly used properties (like valid and dirty) also exist on the control 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'; } }
      
      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';
  }
}
    

當在 <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 } }
      
      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
  }
}
    

在表單組中使用獨立 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. 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: ''} -->
      
      <form>
  <my-custom-form-control name="Nancy" ngModel [ngModelOptions]="{name: 'user'}">
  </my-custom-form-control>
</form>
<!-- form value: {user: ''} -->
    

方法

設定檢視模型的新值併發出 ngModelChange 事件。

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

viewToModelUpdate(newValue: any): void
      
      viewToModelUpdate(newValue: any): void
    
引數
newValue any

ngModelChange 發出的新值。

The new value emitted by ngModelChange.

返回值

void

繼承自 NgControl

繼承自 AbstractControlDirective