简体   繁体   English

在Angular2表单中使用NgForm和NgControlGroup

[英]Using NgForm and NgControlGroup in Angular2 Forms

I can code forms with one ControlGroup but I'm having trouble with multiple ControlGroups. 我可以使用一个ControlGroup编码表单,但是遇到多个ControlGroup的麻烦。 According to the example code, NgControlGroup should be used inside <div> elements and NgForm should be used in the <form> element. 根据示例代码,应在<div>元素内使用NgControlGroup,并在<form>元素内使用NgForm。 So here's my markup: 所以这是我的标记:

<form ng-form="main" (ng-submit)="handleSubmit()">
  <div ng-control-group="group1" >
    <input ng-control="c1"><br /><br />
    <input ng-control="c2"><br /><br />
  </div>
  <div ng-control-group="group2">
    <input ng-control="c3"><br /><br />
    <input ng-control="c4"><br /><br />
  </div>  
  <input type="submit" value="Submit">
</form>

Here's the code for the component's constructor: 这是组件构造函数的代码:

  constructor() {
    this.group1 = new ControlGroup({
      "c1": new Control("first"), 
      "c2": new Control("second")});

    this.group2 = new ControlGroup({
      "c3": new Control("third"), 
      "c4": new Control("fourth")});

    this.main = new ControlGroup({
      "g1": this.group1, "g2": this.group2});
  }

I don't get any errors when I launch the component, but the controls don't take their initial values ("first", "second", and so on). 启动组件时没有出现任何错误,但是控件没有采用它们的初始值(“第一个”,“第二个”等等)。 That means the HTML elements aren't being properly bound to the Controls. 这意味着HTML元素未正确绑定到控件。 Any thoughts? 有什么想法吗? Are there any good examples that use NgForm and NgControlGroup? 是否有使用NgForm和NgControlGroup的良好示例?

I figured out what was wrong. 我弄清楚出了什么问题。 The NgModelForm directive should be used instead of NgModel. 应该使用NgModelForm指令代替NgModel。 Also, the <input> elements should mention the proper names of the ControlGroup s. 另外, <input>元素应提及ControlGroup的专有名称。 Here's the result: 结果如下:

<form [ng-form-model]="main" (ng-submit)="handleSubmit()">
  <div ng-control-group="g1" >
    <input ng-control="c1"><br /><br />
    <input ng-control="c2"><br /><br />
  </div>
  <div ng-control-group="g2">
    <input ng-control="c3"><br /><br />
    <input ng-control="c4"><br /><br />
  </div>  
  <input type="submit" value="Submit">
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM