The official Angular docs have a dynamic form tutorial containing a story for dynamic forms. A service is used to create the FormGroup object like so:
toFormGroup(questions: QuestionBase<any>[] ) {
let group: any = {};
questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
: new FormControl(question.value || '');
});
return new FormGroup(group);
}
How can I add more than one validator function to each FormControl object? The following doesn't seem to work:
questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', [Validators.required, Validators.maxLength(12)])
: new FormControl(question.value || '');
});
I've also tried Validators.compose([Validators.required, Validators.maxLength(12)]) which doesn't work as expected either. The only validator that seems to be applied is the 'required' validator. Here is a plnkr demonstrating the behavior. The code mentioned above is contained in the question-control.service.ts file.
The expected outcome i'm trying to achieve is to have the maxLength validator also applied to the FirstName control.