Created
January 4, 2018 15:59
-
-
Save NicholasMurray/c15697b03c4afca4855b671d20666c03 to your computer and use it in GitHub Desktop.
first-reactive-form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Input, OnInit } from '@angular/core'; | |
import { FormGroup, FormControl, Validators } from '@angular/forms'; | |
@Component({ | |
selector: 'app-first-reactive-form', | |
templateUrl: './first-reactive-form.component.html', | |
styleUrls: ['./first-reactive-form.component.css'] | |
}) | |
export class FirstReactiveFormComponent implements OnInit { | |
form: FormGroup; | |
@Input() formDataObj; | |
personProps = []; | |
ngOnInit() { | |
const formDataObj = {}; | |
for (const prop of Object.keys(this.formDataObj)) { | |
formDataObj[prop] = new FormControl( | |
this.formDataObj[prop].value, | |
this.mapValidator(this.formDataObj[prop].validators) | |
); | |
this.personProps.push({ | |
key: prop, | |
label: this.formDataObj[prop].label, | |
type: this.formDataObj[prop].type, | |
options: this.formDataObj[prop].options | |
}); | |
} | |
this.form = new FormGroup(formDataObj); | |
} | |
mapValidator(validators) { | |
if (validators) { | |
return Object.keys(validators).map(validationType => { | |
if (validationType === 'required') { | |
return Validators.required; | |
} else if (validationType === 'min') { | |
return Validators.min(validators[validationType]); | |
} | |
}); | |
} else { | |
return []; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment