带有 ngmodel 的 Angular 2 动态表单示例导致“检查后表达式已更改" [英] Angular 2 dynamic forms example with ngmodel results in "expression has changed after it was checked"

查看:18
本文介绍了带有 ngmodel 的 Angular 2 动态表单示例导致“检查后表达式已更改"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用提供的这个示例在 Angular 文档中结合使用动态表单和 [(ngmodel)].以便动态表单控件可以绑定到模型.

I'm looking to use this example provided in the Angular documentation to leverage Dynamic forms in combination with the [(ngmodel)]. so that dynamic form controls can be bound to an model.

但是,当我尝试将控件绑定到 [(ngMode)] 时,我看到错误消息

However, when I try to bind a control to [(ngMode)], I see the error message

检查后表达发生了变化.以前的值:'假'.当前值:'真'.

Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

这里是一个示例 Plunker,其中做了一些更改.

Here is an sample Plunker with the changes made.

我修改了 QuestionBase 类来保存一个键

I modified the QuestionBase class to hold a key

export class QuestionBase<T>{
      ...
      modelKey:string;
      ...
}

在 QuestionService 中,每个问题现在都有它应该更新的模型的名称

Within the QuestionService, each question now has the name of the model it should update

  new TextboxQuestion({
          ...
          modelKey: 'firstName'
  }),

在 DynamicFormQuestionComponent 中,模型作为输入变量传入

In the DynamicFormQuestionComponent the model is passed in as an input varialbe

  export class DynamicFormQuestionComponent {
        ...
        @Input() model: SampleModel;
        ...
  }

DynamicFormQuestionComponent HTML 字段已修改为使用 [(ngModel)]

The DynamicFormQuestionComponent HTML fields have been modified to use [(ngModel)]

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

这里的控件应该绑定到解析的'model[question.modelKey]'

Here the control should be bound to the the resolved 'model[question.modelKey]'

鉴于我没有看到官方文档中提供的示例中使用了 [(ngModel)].

Given that I don't see [(ngModel)] used in the example provided in the official documentation.

感谢任何帮助.

谢谢.

推荐答案

很高兴您发现它对您有所帮助.. 以后我会把这个留给其他人..

I'm glad you found it helpful.. I'll just leave this here for others in future..

双向绑定 ngModel 是为模板驱动的表单而设计的比动态反应形式.

Two-way-bound ngModel is designed for template driven forms rather than the dynamic reactive forms.

以下资源将有助于您对比如何做模板驱动"方式与动态反应"方式的对比:

The following resources will be useful to help you contrast how to do things the "template driven" way vs the "dynamic reactive" way:

这篇关于带有 ngmodel 的 Angular 2 动态表单示例导致“检查后表达式已更改"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆