PriNcee
PriNcee

Reputation: 2607

Angular 2 submitting dynamic form

My DB has Questions, every question has 1-N questionTypes and a question with a questionType has 0-N possible answers

enter image description here

Im trying to implement a form with Angular 2 like this plnkr where I can insert as many answers(label+value) as I want with the add button and then save the answers for individual type with the save button.

The problem is that I dont know how to finish It, ¿any help?

Upvotes: 1

Views: 635

Answers (1)

Chrillewoodz
Chrillewoodz

Reputation: 28318

You must use FormBuilder if you want to use arrays in a form:

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

constructor(private fb: FormBuilder} {}

public questionsForm: FormGroup = this.fb.group({
  questions: this.fb.array([])
});

addInfo(label: string, value: string): void {

  const questions: FormArray = <FormArray>this.questionsForm.get('questions');

  questions.push(this.fb.group({label: label, value: value}));

  this.label = '';
  this.value = '';
}

saveQuestion(): void {

  // This will give you {questions: [{label: '', value: ''}, ...]}
  const formValue = this.questionsForm.value;
}

And then template:

<form [formGroup]="questionsForm" (ngSubmit)="saveQuestion()" novalidate>
  <div *ngFor="let info of questionForm.get('questions').controls" [formGroup]="info">
    <input formControlName="label>
    <input formControlName="value">
  </div>

  <input [(ngModel]="label" [ngModelOptions]="{standalone: true}" type="text" placeholder="label">
  <input [(ngModel]="value" [ngModelOptions]="{standalone: true}" type="text" placeholder="value">

  <button (click)="addInfo(label, value)">Add</button>

  <p>
    <button type="submit">Save Question</button>
  </p>
</form>

Upvotes: 1

Related Questions