[formControlName] directive

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

Register FormControl within a group

The following example shows how to register multiple form controls within a form group and set their value.

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'}); }
}

Interface, extends NgControl

control#

control: FormControl

Tracks the FormControl instance bound to the directive.

name#

@Input('formControlName') name: string | number | null

Tracks the name of the FormControl bound to the directive. The name corresponds to a key in the parent FormGroup or FormArray. Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in a FormArray.

isDisabled#

@Input('disabled') set isDisabled(isDisabled: boolean)

Triggers a warning that this input should not be used with reactive forms.

model#

@Input('ngModel') model: any

update#

@Output('ngModelChange') update

viewToModelUpdate#

viewToModelUpdate(newValue: any): void

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

path#

get 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#

get formDirective(): any

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

validator#

get validator(): ValidatorFn|null

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

asyncValidator#

get asyncValidator(): AsyncValidatorFn

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