NgForm • Angular

API

    
      class NgForm extends ControlContainer implements Form ,AfterViewInit {  constructor(validators: (ValidatorFn | Validator)[], asyncValidators: (AsyncValidatorFn | AsyncValidator)[], callSetDisabledState?: SetDisabledStateOption | undefined): NgForm;  readonly submitted: boolean;  form: FormGroup<any>;  @Output() ngSubmit: EventEmitter<any>;  @Input('ngFormOptions') options: { updateOn?: FormHooks | undefined; };  readonly formDirective: Form;  readonly control: FormGroup<any>;  readonly path: string[];  readonly controls: { [key: string]: AbstractControl<any, any, any>; };  addControl(dir: NgModel): void;  getControl(dir: NgModel): FormControl<any>;  removeControl(dir: NgModel): void;  addFormGroup(dir: NgModelGroup): void;  removeFormGroup(dir: NgModelGroup): void;  getFormGroup(dir: NgModelGroup): FormGroup<any>;  updateModel(dir: NgControl, value: any): void;  setValue(value: { [key: string]: any; }): void;  onSubmit($event: Event): boolean;  onReset(): void;  resetForm(value?: any): void;  override name: string | number | null;  override readonly value: any;  override readonly valid: boolean | null;  override readonly invalid: boolean | null;  override readonly pending: boolean | null;  override readonly disabled: boolean | null;  override readonly enabled: boolean | null;  override readonly errors: ValidationErrors | null;  override readonly pristine: boolean | null;  override readonly dirty: boolean | null;  override readonly touched: boolean | null;  override readonly status: string | null;  override readonly untouched: boolean | null;  override readonly statusChanges: any;  override readonly valueChanges: any;  override readonly validator: ValidatorFn | null;  override readonly asyncValidator: AsyncValidatorFn | null;  override reset(value?: any): void;  override hasError(errorCode: string, path?: string | (string | number)[] | undefined): boolean;  override getError(errorCode: string, path?: string | (string | number)[] | undefined): any;}
    
    

Returns whether the form submission has been triggered.

The FormGroup instance created for this form.

Event emitter for the "ngSubmit" event

Tracks options for the NgForm instance.

updateOn: Sets the default updateOn value for all child NgModels below it unless explicitly set by a child NgModel using ngModelOptions). Defaults to 'change'. Possible values: 'change' | 'blur' | 'submit'.

Returns an array representing the path to this group. Because this directive always lives at the top level of a form, it is always an empty array.

Returns a map of the controls in this group.

Method that sets up the control directive in this group, re-calculates its value and validity, and adds the instance to the internal list of directives.

@returnsvoid

Removes the NgModel instance from the internal list of directives

@returnsvoid

Adds a new NgModelGroup directive instance to the form.

@returnsvoid

Removes the NgModelGroup directive instance from the form.

@returnsvoid

Sets the new value for the provided NgControl directive.

@paramvalueany

The new value for the directive's control.

@returnsvoid

@paramvalue{ [key: string]: any; }

The new value

@returnsvoid

Method called when the "submit" event is triggered on the form. Triggers the ngSubmit emitter to emit the "submit" event as its payload.

@param$eventEvent

The "submit" event object

@returnsboolean

Method called when the "reset" event is triggered on the form.

@returnsvoid

Resets the form to an initial value and resets its submitted status.

@paramvalueany

The new value for the form.

@returnsvoid

Reports the value of the control if it is present, otherwise null.

Reports whether the control is valid. A control is considered valid if no validation errors exist with the current value. If the control is not present, null is returned.

Reports whether the control is invalid, meaning that an error exists in the input value. If the control is not present, null is returned.

Reports whether a control is pending, meaning that async validation is occurring and errors are not yet available for the input value. If the control is not present, null is returned.

Reports whether the control is disabled, meaning that the control is disabled in the UI and is exempt from validation checks and excluded from aggregate values of ancestor controls. If the control is not present, null is returned.

Reports whether the control is enabled, meaning that the control is included in ancestor calculations of validity or value. If the control is not present, null is returned.

Reports the control's validation errors. If the control is not present, null is returned.

Reports whether the control is pristine, meaning that the user has not yet changed the value in the UI. If the control is not present, null is returned.

Reports whether the control is dirty, meaning that the user has changed the value in the UI. If the control is not present, null is returned.

Reports whether the control is touched, meaning that the user has triggered a blur event on it. If the control is not present, null is returned.

Reports the validation status of the control. Possible values include: 'VALID', 'INVALID', 'DISABLED', and 'PENDING'. If the control is not present, null is returned.

Reports whether the control is untouched, meaning that the user has not yet triggered a blur event on it. If the control is not present, null is returned.

Returns a multicasting observable that emits a validation status whenever it is calculated for the control. If the control is not present, null is returned.

Returns a multicasting observable of value changes for the control that emits every time the value of the control changes in the UI or programmatically. If the control is not present, null is returned.

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

Asynchronous validator function composed of all the asynchronous validators registered with this directive.

Resets the control with the provided value if the control is present.

@returnsvoid

Reports whether the control with the given path has the error specified.

@paramerrorCodestring

The code of the error to check

@parampathstring | (string | number)[] | undefined

A list of control names that designates how to move from the current control to the control that should be queried for errors.

@returnsboolean

Usage notes

For example, for the following FormGroup:

The path to the 'street' control from the root form would be 'address' -> 'street'.

It can be provided to this method in one of two formats:

  1. An array of string control names, e.g. ['address', 'street']
  2. A period-delimited list of control names in one string, e.g. 'address.street'

If no path is given, this method checks for the error on the current control.

Reports error data for the control with the given path.

@paramerrorCodestring

The code of the error to check

@parampathstring | (string | number)[] | undefined

A list of control names that designates how to move from the current control to the control that should be queried for errors.

@returnsany

Usage notes

For example, for the following FormGroup:

The path to the 'street' control from the root form would be 'address' -> 'street'.

It can be provided to this method in one of two formats:

  1. An array of string control names, e.g. ['address', 'street']
  2. A period-delimited list of control names in one string, e.g. 'address.street'

Description

Creates a top-level FormGroup instance and binds it to a form to track aggregate form value and validation status.

As soon as you import the FormsModule, this directive becomes active by default on all <form> tags. You don't need to add a special selector.

You optionally export the directive into a local template variable using ngForm as the key (ex: #myForm="ngForm"). This is optional, but useful. Many properties from the underlying FormGroup instance are duplicated on the directive itself, so a reference to it gives you access to the aggregate value and validity status of the form, as well as user interaction properties like dirty and touched.

To register child controls with the form, use NgModel with a name attribute. You may use NgModelGroup to create sub-groups within the form.

If necessary, listen to the directive's ngSubmit event to be notified when the user has triggered a form submission. The ngSubmit event emits the original form submission event.

In template driven forms, all <form> tags are automatically tagged as NgForm. To import the FormsModule but skip its usage in some forms, for example, to use native HTML5 validation, add the ngNoForm and the <form> tags won't create an NgForm directive. In reactive forms, using ngNoForm is unnecessary because the <form> tags are inert. In that case, you would refrain from using the formGroup directive.


Exported by

Usage Notes

Listening for form submission

The following example shows how to capture the form values from the "ngSubmit" event.

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

Setting the update options

The following example shows you how to change the "updateOn" option from its default using ngFormOptions.

<form [ngFormOptions]="{updateOn: 'blur'}">   <input name="one" ngModel>  <!-- this ngModel will update on blur --></form>

Native DOM validation UI

In order to prevent the native DOM form validation UI from interfering with Angular's form validation, Angular automatically adds the novalidate attribute on any <form> whenever FormModule or ReactiveFormModule are imported into the application. If you want to explicitly enable native DOM validation UI with Angular forms, you can add the ngNativeValidate attribute to the <form> element:

<form ngNativeValidate>  ...</form>