W3cubDocs

/Angular

FormControlName

directive stable

Syncs a FormControl in an existing FormGroup to a form control element by name.

@Directive({ selector: '[formControlName]', providers: [controlNameBinding] })
class FormControlName extends NgControl implements OnChanges, OnDestroy {
  constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null)
  get control: FormControl
  name: string
  set isDisabled: boolean
  model: any
  update: new EventEmitter()
  get path: string[]
  get formDirective: any
  get validator: ValidatorFn | null
  get asyncValidator: AsyncValidatorFn
  ngOnChanges(changes: SimpleChanges)
  ngOnDestroy(): void
  viewToModelUpdate(newValue: any): void

  // inherited from forms/NgControl
  name: string | null
  valueAccessor: ControlValueAccessor | null
  get validator: ValidatorFn | null
  get asyncValidator: AsyncValidatorFn | null
  abstract viewToModelUpdate(newValue: any): void

  // inherited from forms/AbstractControlDirective
  abstract get control: AbstractControl | null
  get value: any
  get valid: boolean | null
  get invalid: boolean | null
  get pending: boolean | null
  get disabled: boolean | null
  get enabled: boolean | null
  get errors: ValidationErrors | null
  get pristine: boolean | null
  get dirty: boolean | null
  get touched: boolean | null
  get status: string | null
  get untouched: boolean | null
  get statusChanges: Observable<any> | null
  get valueChanges: Observable<any> | null
  get path: string[] | null
  reset(value: any = undefined): void
  hasError(errorCode: string, path?: string[]): boolean
  getError(errorCode: string, path?: string[]): any
}

Selectors

[formControlName]

Inputs

disabled bound to FormControlName.isDisabled

Outputs

ngModelChange bound to FormControlName.update

Description

This directive ensures that any values written to the FormControl instance programmatically will be written to the DOM element (model -> view). Conversely, any values written to the DOM element through user input will be reflected in the FormControl instance (view -> model).

This directive is designed to be used with a parent FormGroupDirective (selector: [formGroup]).

It accepts the string name of the FormControl instance you want to link, and will look for a FormControl registered with that name in the closest FormGroup or FormArray above it.

Access the control: You can access the FormControl associated with this directive by using the get method. Ex: this.form.get('first');

Get value: the value property is always synced and available on the FormControl. See a full list of available properties in AbstractControl.

Set value: You can set an initial value for the control when instantiating the FormControl, or you can set it programmatically later using setValue or patchValue.

Listen to value: If you want to listen to changes in the value of the control, you can subscribe to the valueChanges event. You can also listen to statusChanges to be notified when the validation status is re-calculated.

Example

In this example, we create form controls for first name and last name.

import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit()">
      <div *ngIf="first.invalid"> Name is too short. </div>

      <input formControlName="first" placeholder="First name">
      <input formControlName="last" placeholder="Last name">

      <button type="submit">Submit</button>
   </form>
   <button (click)="setValue()">Set preset value</button>
  `,
})
export class SimpleFormGroup {
  form = new FormGroup({
    first: new FormControl('Nancy', Validators.minLength(2)),
    last: new FormControl('Drew'),
  });

  get first(): any { return this.form.get('first'); }

  onSubmit(): void {
    console.log(this.form.value);  // {first: 'Nancy', last: 'Drew'}
  }

  setValue() { this.form.setValue({first: 'Carson', last: 'Drew'}); }
}

To see formControlName examples with different form control types, see:

npm package: @angular/forms

NgModule: ReactiveFormsModule

Use with ngModel

Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7.

Now deprecated:

<form [formGroup]="form">
  <input formControlName="first" [(ngModel)]="value">
</form>
this.value = 'some value';

This has been deprecated for a few reasons. First, developers have found this pattern confusing. It seems like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work, which has understandably caused some confusion.

In addition, this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. Setting the value in the template violates the template-agnostic principles behind reactive forms, whereas adding a FormControl/FormGroup layer in the class removes the convenience of defining forms in the template.

To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

After (choice 1 - use reactive forms):

<form [formGroup]="form">
  <input formControlName="first">
</form>
this.form.get('first').setValue('some value');

After (choice 2 - use template-driven forms):

<input [(ngModel)]="value">
this.value = 'some value';

By default, when you use this pattern, you will see a deprecation warning once in dev mode. You can choose to silence this warning by providing a config for ReactiveFormsModule at import time:

imports: [
  ReactiveFormsModule.withConfig({warnOnNgModelWithFormControl: 'never'});
]

Alternatively, you can choose to surface a separate warning for each instance of this pattern with a config value of "always". This may help to track down where in the code the pattern is being used as the code is being updated.

Constructor

constructor(parent: ControlContainer, validators: Array<Validator | ValidatorFn>, asyncValidators: Array<AsyncValidator | AsyncValidatorFn>, valueAccessors: ControlValueAccessor[], _ngModelWarningConfig: string | null)

Parameters

parent

Type: ControlContainer.

validators

Type: Array.

asyncValidators

Type: Array.

valueAccessors

Type: ControlValueAccessor[].

_ngModelWarningConfig

Type: string | null.

Properties

Property Type Description
control FormControl Read-only.
name string
isDisabled boolean
model any
update new EventEmitter()
path string[] Read-only.
formDirective any Read-only.
validator ValidatorFn | null Read-only.
asyncValidator AsyncValidatorFn Read-only.

Methods

ngOnChanges()

ngOnChanges(changes: SimpleChanges)

Parameters

changes

Type: SimpleChanges.

ngOnDestroy()

ngOnDestroy(): void

Parameters

There are no parameters.

Returns

void

viewToModelUpdate()

viewToModelUpdate(newValue: any): void

Parameters

newValue

Type: any.

Returns

void

© 2010–2018 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/api/forms/FormControlName