Angular 2动态表单 - 实现清晰功能

时间:2016-08-03 00:01:20

标签: javascript forms typescript angular angular2-forms

我正在尝试为Angualr 2动态表单实现Clear功能,它应该清除所有值为null。但是,当我尝试使用this.questions[i].value="null";this.questions[i].value="undefinded";this.questions[i].value='';替换表单中的每个值时,我收到错误。

工作代码:http://plnkr.co/edit/SL949g1hQQrnRUr1XXqt?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 = 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 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>
      <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>

有没有办法可以在不收到错误的情况下完成。

1 个答案:

答案 0 :(得分:2)

如果需要字段,问题在于检查和显示消息的逻辑。 你的plunker代码抛出异常Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'

问题在于它使用问题[i] .value的值运行模板代码,但一旦调用clear就会更改。 Angular比较问题[i] .value并注意它与开始渲染时的不同之处并认为它是错误的。它没有发现你改变了价值。你必须让它知道价值已被改变。

如果您在启用prod的情况下运行代码,它将不会运行此安全检查并且您不会收到任何错误,但启用prod模式只是为了解决此问题。< / p>

<强>解决方案

此修复程序从ChangeDetectorRef导入@angular/core到dynamic.form.component.ts

private cdr: ChangeDetectorRef添加到构造函数

并将this.cdr.detectChanges();添加到clear()方法的末尾。

这将让我们知道角度提升已发生变化,并且不会认为这是错误的

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 || ''); });