Angular 6 reactive form example fails on plunker

I have the following example of angular 6:

//our root app component
import { Component, NgModule, VERSION, Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { FormsModule, ReactiveFormsModule, FormArray, FormBuilder } from '@angular/forms';


@Component({
  selector: 'my-app',
  template: `<form [formGroup]="form" novalidate="">
  <div style="margin-bottom:80px">
    <div *ngFor="let item of form.controls; let idx=index" [formGroupName]="idx">
    <div *ngIf='item.controls.type.value == "control"'>
    <div>Input</div>
      <input name="answer" type="text" placeholder="Reponse" formControlName="answer"/>
    </div>
    <div *ngIf='item.controls.type.value == "group"' formGroupName="answer">
    <div>Checkboxes</div>
    <div *ngFor='let ctrl of item.controls.answer.controls; let index=index'>
      <input name="answer" type="checkbox" placeholder="Reponse" [formControlName]="index"/>
    </div>
    </div>
    </div>
  </div>
  <button type="button" (click)="changeTemplate()">New template</button>
</form>`
})

export class App {
    private form:FormArray;

  constructor(private formBuilder:FormBuilder){

  }


  changeTemplate(){

    this.form = this.formBuilder.array([
      this.formBuilder.group({
        answer:[''],
        type:['control']
      }),
      this.formBuilder.group({
        answer:this.formBuilder.array([[''], [''], ['']]),
        type:['group']
      }),
      this.formBuilder.group({
        answer:[''],
        type:['control']
      })
      ]);


  }

  ngOnInit(){
    this.form = this.formBuilder.array([
      this.formBuilder.group({
        answer:this.formBuilder.array([[''], [''], ['']]),
        type:['group']
      }),
      this.formBuilder.group({
        answer:[''],
        type:['control']
      }),
      this.formBuilder.group({
        answer:this.formBuilder.array([[''], [''], ['']]),
        type:['group']
      })
      ]);


  }
}

@NgModule({
    imports: [BrowserModule, ReactiveFormsModule],
    declarations: [App],
    bootstrap: [App],
})
export class AppModule {}

And get the following error on plunker:

Can't resolve all parameters for App: (?).

Here is the plunker: http://next.plnkr.co/edit/hmUZdqTR8hpxHj0w?open=lib%2Fapp.ts&deferRun=1&preview

Does anyone know how to fix this?

1 answer

  • answered 2018-11-08 01:20 Sunil Singh

    Add @Inject decorator in App class constructor

    export class App {
      private form:FormArray;
    
      constructor(@Inject(FormBuilder) private formBuilder: FormBuilder){
    
      }
      ....
    }