Dynamic / Reactive Forms Error - Angular 2

448 views Asked by At

I followed the Reactive Forms Guide on the Angular 2 website. https://angular.io/docs/ts/latest/cookbook/dynamic-form.html

However, I'm having trouble with adding new questions as it gives me the following error:

EXCEPTION: Error in http://10.1.6.78/hira/app/dynamic-form-question.component.php:9:28 caused by: Cannot read property 'valid' of undefined

It is most likely related to the creation of the questions as the following code works:

default: QuestionBase<any>[] = [ 
  new DropdownQuestion({
    key: 'brave',
    label: 'Bravery Rating',
    options: [
      {key: 'solid',  value: 'Solid'},
      {key: 'great',  value: 'Great'},
      {key: 'good',   value: 'Good'},
      {key: 'unproven', value: 'Unproven'}
    ],  
    order: 3
  }), 
  new TextboxQuestion({
    key: 'firstName',
    label: 'First name',
    value: 'Bombasto',
    required: true,
    order: 1
  }), 
  new TextboxQuestion({
    key: 'emailAddress',
    label: 'Email',
    type: 'email',
    order: 2
  })  
];

but this code gives the error:

start: QuestionBase<any>[] = [
  new TextboxQuestion({
    key: 'firstName',
    label: 'First name',
    value: 'Bombasto',
    order: 1
  }), 

  new TextboxQuestion({
    key: 'secondName',
    label: 'Second name',
    value: 'Bombasto',
    order: 2
  }), 
];  
1

There are 1 answers

0
A. L On BEST ANSWER

Okay, the undefined thing was because the this.form thing in dynamic-form.component.ts wasn't being set properly. So I added this:

ngOnChanges(changes: SimpleChange) 
{   
    this.form = this.qcs.toFormGroup(this.questions);   
}

and now it works on change.