我试图实现取消功能,该功能应该恢复到表单中的上一个值,这些值在上次提交表单时出现。我正在尝试创建传递给表单的数据对象的副本,并且在提交功能中我将新值替换为副本,并在“取消”功能中,我正在尝试创建数据对象的副本。 m将复制值替换为原始值。但是当我调用取消功能时,我没有得到以前的值。
包含错误的工作代码:http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview
我根据Angualr 2表单的模板驱动代码实现了取消功能:http://plnkr.co/edit/LCAPYTZElQDjrSgh3xnT?p=preview
Typescript类代码:
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';
@Component({
selector: 'dynamic-form',
templateUrl: 'app/dynamic-form.component.html',
directives: [REACTIVE_FORM_DIRECTIVES],
providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {
@Input() questions: QuestionBase<any>[] = [];
form: FormGroup;
payLoad:object;
questiont: QuestionBase<any>;
constructor(private qcs: QuestionControlService) { }
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions);
console.log("Form Init",this.questions);
this.questiont=this.questions;
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.payLoad2=this.payLoad;
this.questiont=this.questions;
console.log("Original Data",this.questions);
console.log("Duplicate Data",this.questiont);
}
cancel(){
this.questions=this.questiont;
console.log("Original Data",this.questions);
console.log("Duplicate Data",this.questiont);
console.log("Canceled");
}
}
HTML code:
<div>
<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>
</select>
</div>
<div class="errorMessage" *ngIf="!form.controls[question.key].valid">{{question.label}} is required</div>
</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>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
任何人遇到此问题或尝试实施此操作。
答案 0 :(得分:5)
表格重置将在RC5中实施。
您的方法不适用于对象:
this.questiont=this.questions; //you are sharing refrence to the same object
你应该克隆对象(有很多方法可以做到这一点,我正在使用JSON):
this.questiont = JSON.parse(JSON.stringify(this.questions));