Skip to content

Instantly share code, notes, and snippets.

@johnrsimoneau
Last active May 3, 2018 18:11
Show Gist options
  • Save johnrsimoneau/90c16fb072b3f4294039d08e9e457984 to your computer and use it in GitHub Desktop.
Save johnrsimoneau/90c16fb072b3f4294039d08e9e457984 to your computer and use it in GitHub Desktop.
Building the reactive-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html'
})
export class ReactiveFormComponent implements OnInit {
constructor(private fb: FormBuilder) { }
bookForm: FormGroup;
bookTitle: AbstractControl;
firstName: AbstractControl;
lastName: AbstractControl;
emailAddress: AbstractControl;
genre: AbstractControl;
bookRead: AbstractControl;
maxBookLength: number = 50;
ngOnInit() {
this.initializeForm();
}
initializeForm() {
this.bookForm = this.fb.group({
bookTitle: ['Anything in here will display inside the input', Validators.compose([
Validators.required,
Validators.maxLength(this.maxBookLength)
])],
firstName: ['', Validators.required],
lastName: ['', Validators.required],
emailAddress: ['', Validators.compose([
Validators.required,
this.emailValidator
])],
genre: ['', Validators.required],
bookRead: [true]
});
this.bookTitle = this.bookForm.controls['bookTitle'];
this.firstName = this.bookForm.controls['firstName'];
this.lastName = this.bookForm.controls['lastName'];
this.emailAddress = this.bookForm.controls['emailAddress'];
this.genre = this.bookForm.controls['genre'];
this.bookRead = this.bookForm.controls['bookRead'];
}
emailValidator(control: FormControl): { [s: string]: boolean } {
if (!control.value.match(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
return { invalidEmail: true };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment