handle users input as a form
represents a single input field
let firstname = new FormControl(); // Create a FormControl
console.log(firstname.value); // Get the current value
console.log(firstname.errors); // Get validation errors
console.log(firstname.dirty); // Check if the value has changed
console.log(firstname.touched); // Check if the field has been touched
is a collection of FormControls
let address = new FormGroup({
name: new FormControl({ value: 'Rahul', disabled: true }),
city: new FormControl(""),
pinCode: new FormControl('', [Validators.required, Validators.minLength(6), Validators.email])
});
console.log(address.value); // Get the form values as a JSON object
console.log(address.get("city")); // Access specific FormControl
array of formControls
let phoneNumbers = new FormArray([
new FormControl(''),
new FormControl('')
]);
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
<input type="text" name="firstname" ngModel #fname="ngModel">
<button type="submit">Submit</button>
</form>
<!-- contactForm is formGroup, have methods like value, valid, touched,submitted -->
<!-- fname is formControl, have methods like value, valid, invalid,touched -->
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<input type="text" id="firstname" name="firstname" formControlName="firstname">
<input type="text" id="lastname" name="lastname" [formControl]="lastname">
<button type="submit">Submit</button>
</form>
A convenient way to create forms.
constructor(private formBuilder: FormBuilder) { }
this.contactForm = this.formBuilder.group({
firstname: [''],
lastname: [''],
email: ['']
});
required, minLength, maxLength, and custom validators can also be created.
let emailControl = new FormControl('', [Validators.required, Validators.email]);