【问题标题】:Angular 2 - NgForm null when submit a formAngular 2 - 提交表单时 NgForm null
【发布时间】:2017-07-08 12:15:46
【问题描述】:

大家好,我正在使用 Angular 做一个“动态”表单,我在获取表单中输入的值时遇到了一些问题,我的代码是:

HTML

<form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" *ngFor="let con of controls" novalidate>
  <div class="form-group" *ngIf = "con.type != 'submit'">
    <label for="{{con.id}}">{{con.label}}</label>
    <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}">
 </div>
 <input  *ngIf = "con.type == 'submit'"  type="submit" class="{{con.class}}" value={{con.label}}> 
</form> 

组件:

import { Component ,Input} from '@angular/core';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'form-tag',
  templateUrl: './form.html',
})

export class FormComponent {
    @Input() controls: any[];

    onSubmit(sub: NgForm)
    {
        console.log(sub.email);
    }
}

问题是当我提交表单时 console.log(sub.email);返回一个空对象

【问题讨论】:

    标签: angular


    【解决方案1】:

    由于您使用 ngForm,它是模板驱动的表单,而不是响应式表单。在模板驱动的表单中,您需要将 myForm.value 传递给 onSubmit():

    onSubmit(myForm.value)
    

    另外,从您的代码示例中,不清楚是什么。

    【讨论】:

      【解决方案2】:

      我不太确定您要做什么,但您似乎正在循环使用 &lt;form&gt; 标签而不是 div.form-group&lt;input /&gt; 本身的控件。

      也许将它们包装在 &lt;ng-template /&gt; 中并循环遍历它而不是 &lt;form&gt; 标记?

      所以是这样的:

      <form  #myForm="ngForm" (ngSubmit)="onSubmit(myForm)" novalidate>
          <ng-template *ngFor="let con of controls">
            <div class="form-group" *ngIf="con.type != 'submit'">
              <label for="{{con.id}}">{{con.label}}</label>
              <input [(ngModel)]="con.name" type="{{con.type}}" class="{{con.class}}" name="{{con.id}}" />
           </div>
           <input *ngIf="con.type == 'submit'" type="submit" class="{{con.class}}" [value]="con.label" />
      </form> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        • 2018-06-20
        • 1970-01-01
        • 2017-03-06
        • 2016-06-24
        相关资源
        最近更新 更多