Angular2(ngSubmit)不起作用

时间:2016-12-14 09:53:51

标签: angular angular2-forms angular2-directives

我刚刚启动Angular2并在向表单添加(ngSubmit)属性时遇到以下错误

Template parse errors:
There is no directive with "exportAs" set to "ngForm" ("


    <form [ERROR ->]#form="ngForm" (ngSubmit)="onSubmit()" novalidate>

以下是来自package.json的一些依赖项。

"dependencies": {
    "@angular/common": "2.0.0",
    "@angular/compiler": "2.0.0",
    "@angular/core": "2.0.0",
    "@angular/forms": "2.0.0",
    "@angular/http": "2.0.0",
    "@angular/platform-browser": "2.0.0",
    "@angular/platform-browser-dynamic": "2.0.0",
    "@angular/router": "3.0.0",
    "@angular/upgrade": "2.0.0",
    "angular2-in-memory-web-api": "0.0.20",
    "core-js": "^2.4.1",
    "ie-shim": "^0.1.0",
    "jquery": "^3.1.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.27",
    "zone.js": "^0.6.23"
  }

我关注的是html表单。

<form #form="ngForm" (ngSubmit)="onSubmit()" novalidate>

    <div class="form-group">
        <label>Title</label>
        <input [(ngModel)]="model.Title" #title="ngModel" name="title" id="title" type="text" class="form-control" value="">
    </div>

    <div class="form-group">
        <label>Description</label>
        <textarea [(ngModel)]="model.Description" #description="ngModel" class="summernote form-control" name="description" id="description"></textarea>
    </div>

</form>

关注 category.component 文件

import { Component } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Category } from '../../../models/cms/Category';

@Component({
    selector: 'category',
    templateUrl: 'category.template.html'
})
export class CategoryComponent{

    model = new Category("dummyTitle","dummyDescription");

    onSubmit() {
        console.log(this.data);
    }   
}

有人可以指导如何处理这个问题。

3 个答案:

答案 0 :(得分:8)

您缺少导入文件import { NgForm } from '@angular/forms';

并且您正在使用模板驱动表单,因此您不需要FormBuilder。

试试这种方式

<强>注册-form.component.html

<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
  <label for="email">Email</label>
  <input type="text" name="email" id="email" ngModel>

  <label for="password">Password</label>
  <input type="password" name="password" id="password" ngModel>

  <button type="submit">Sign Up</button>
</form>

<强>注册-form.component.ts

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

@Component({
  selector: 'signup-form',
  templateUrl: 'app/signup-form.component.html',
})
export class SignupForm {
  registerUser(form: NgForm) {
    console.log(form.value);
  }
}

答案 1 :(得分:0)

就我而言,我的<button type="submit">Ok</button>在表单标签之外。 它必须在form标记内才能工作。

<form [formGroup]="myForm" (ngSubmit)="submitHandler()">

    <!-- ... form fields here ... -->

    <button type="submit">Ok</button> <!------- must be inside form -->
</form>

答案 2 :(得分:0)

确保按钮在表单内并且具有类型=“ submit”。例如,

<ion-button type="submit"></ion-button>