Angular 2 动态表单 - 实现清晰的功能
Angular 2 Dynamic Form - Implement Clear Functionality
我正在尝试为 Angualr 2 动态表单实现清除功能,该功能应将所有值清除为 null。但是当我尝试使用 this.questions[i].value="null";
或 this.questions[i].value="undefinded";
或 this.questions[i].value='';
替换表单中的每个值时出现错误。
工作代码:http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview
Typescript class 代码:
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 = JSON.parse(JSON.stringify(this.questions));
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.payLoad2=this.payLoad;
this.questiont = JSON.parse(JSON.stringify(this.questions));
}
cancel(){
console.log("Canceled");
this.questions = JSON.parse(JSON.stringify(this.questiont));
}
clear(){
for(var i=0;i<this.questions.length;i++){
this.questions[i].value='';
}
console.log("Cleared");
}
}
HTML代码:
<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>
<button type="button" class="btn btn-default" (click)="clear()">Clear</button>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
有什么方法可以做到不出错吗?
问题出在您的逻辑上,如果某个字段是必填项,则检查并显示一条消息。
您的 plunker 代码抛出异常 Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'
问题是,它 运行 使用问题 [i].value 的值覆盖了您的模板代码,但是一旦您调用 clear,它就会发生变化。 Angular 比较 questions[i].value 并注意到它与开始渲染时不同,并认为它犯了一个错误。它没有发现你改变了价值。您必须让它知道值已更改。
如果您要 运行 启用产品的代码,它不会 运行 此安全检查并且您不会收到任何错误,但 不要 启用生产模式只是为了解决这个问题。
解决方案
修复方法是将 ChangeDetectorRef
从 @angular/core
导入到 dynamic.form.component.ts
构造函数添加private cdr: ChangeDetectorRef
并将 this.cdr.detectChanges();
添加到 clear()
方法的末尾。
这会让 angular 知道已经发生了变化并且它不会认为它犯了一个错误
P.S. 罪魁祸首是
<div class="errorMessage" *ngIf=" form && !form.controls[question.key].valid">{{question.label}} is required</div>
和
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required) : new FormControl(question.value || ''); });
我正在尝试为 Angualr 2 动态表单实现清除功能,该功能应将所有值清除为 null。但是当我尝试使用 this.questions[i].value="null";
或 this.questions[i].value="undefinded";
或 this.questions[i].value='';
替换表单中的每个值时出现错误。
工作代码:http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?p=preview
Typescript class 代码:
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 = JSON.parse(JSON.stringify(this.questions));
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.payLoad2=this.payLoad;
this.questiont = JSON.parse(JSON.stringify(this.questions));
}
cancel(){
console.log("Canceled");
this.questions = JSON.parse(JSON.stringify(this.questiont));
}
clear(){
for(var i=0;i<this.questions.length;i++){
this.questions[i].value='';
}
console.log("Cleared");
}
}
HTML代码:
<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>
<button type="button" class="btn btn-default" (click)="clear()">Clear</button>
</div>
</form>
<div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>
有什么方法可以做到不出错吗?
问题出在您的逻辑上,如果某个字段是必填项,则检查并显示一条消息。
您的 plunker 代码抛出异常 Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'
问题是,它 运行 使用问题 [i].value 的值覆盖了您的模板代码,但是一旦您调用 clear,它就会发生变化。 Angular 比较 questions[i].value 并注意到它与开始渲染时不同,并认为它犯了一个错误。它没有发现你改变了价值。您必须让它知道值已更改。
如果您要 运行 启用产品的代码,它不会 运行 此安全检查并且您不会收到任何错误,但 不要 启用生产模式只是为了解决这个问题。
解决方案
修复方法是将 ChangeDetectorRef
从 @angular/core
导入到 dynamic.form.component.ts
构造函数添加private cdr: ChangeDetectorRef
并将 this.cdr.detectChanges();
添加到 clear()
方法的末尾。
这会让 angular 知道已经发生了变化并且它不会认为它犯了一个错误
P.S. 罪魁祸首是
<div class="errorMessage" *ngIf=" form && !form.controls[question.key].valid">{{question.label}} is required</div>
和
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required) : new FormControl(question.value || ''); });