Varun Varun - 2 months ago 46
Javascript Question

Angular 2 Dynamic Form - Implement Cancel functionality

I'm trying to implement Cancel functionality which should revert back to the previous values in the form, which were present during the last time the form was submitted. I'm trying to create a copy of the data object that's being passed to the form and in the Submit function i'm replacing the new values to the copy and in Cancel function, i'm replacing the copy values to the original values. But i'm not getting the previous values when i call the cancel function.

Working code with errors:

I implemented the cancel functionality based on the template driven code of Angualr 2 forms:

Typescript class code:

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';

selector: 'dynamic-form',
templateUrl: 'app/dynamic-form.component.html',
providers: [QuestionControlService]
export class DynamicFormComponent implements OnInit {

@Input() questions: QuestionBase<any>[] = [];
form: FormGroup;
questiont: QuestionBase<any>;
constructor(private qcs: QuestionControlService) { }
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
console.log("Form Init",this.questions);
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
console.log("Original Data",this.questions);
console.log("Duplicate Data",this.questiont);
console.log("Original Data",this.questions);
console.log("Duplicate Data",this.questiont);


HTML code:

<form [formGroup]="form">

<div *ngFor="let question of questions" class="form-row">
<label [attr.for]="question.key">{{question.label}}</label>

<div [ngSwitch]="question.controlType">

<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
[id]="question.key" [type]="question.type" [(ngModel)]="question.value">

<select [id]="question.key" [(ngModel)]="question.value" *ngSwitchCase="'dropdown'" [formControlName]="question.key" >
<option *ngFor="let opt of question.options" [ngValue]="opt.key" >{{opt.value}}</option>

<div class="errorMessage" *ngIf="!form.controls[question.key].valid">{{question.label}} is required</div>

<div class="form-row">
<button type="submit" [disabled]="!form.valid" (click)="onSubmit()">Save</button>
<button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>


<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}

Anyone got this problem or tried to implement this.


Form reset will be implemented in RC5.

Your approach does not work with objects:

this.questiont=this.questions; //you are sharing refrence to the same object

You should clone object instead (there are many ways to do that, i'm using JSON):

this.questiont = JSON.parse(JSON.stringify(this.questions));