繁体   English   中英

Angular 4.带有表单模块的问题

[英]Angular 4. Troubles with Forms Module

我从这里举个例子: Angular 4 Forms Directive(ngForm)并得到错误:ngModel和ngForm没有指令。 似乎没有包含指令。

ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "exportAs" set to "NgForm" ("<form (ngSubmit)="onSubmit(f)" [ERROR ->]#f="NgForm" novalidate> <input name="first" [(ngModel)]="first" required #first="ngModel"> .....

core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("
 <form (ngSubmit)="onSubmit(f)" novalidate>
   <input name="first" ngModel required [ERROR ->]#first="ngModel">
   <input name="last" ngModel>
   <button>Submit</button>"): ng:///AuthModule/LoginComponent.html@2:44 Error: Template parse errors: There is no directive with "exportAs" set to "ngModel" ("<form (ngSubmit)="onSubmit(f)" novalidate><input name="first" ngModel required [ERROR ->]#first="ngModel"><input name="last" ngModel><button>Submit</button>"): ng:///AuthModule/LoginComponent.html@2:44
at syntaxError (http://localhost:4200/vendor.bundle.js:50027:34) [angular]....

文件在这里:

模块文件:login.module.ts

     import { NgModule } from '@angular/core';
     import { CommonModule } from '@angular/common';
     import { FormsModule } from '@angular/forms';
     import { BrowserModule } from '@angular/platform-browser';

     import { LoginComponent } from './login.component';
     @NgModule({
         imports: [
             CommonModule,
             FormsModule,
             BrowserModule
         ],
         declarations: [LoginComponent],
         bootstrap: [LoginComponent],
    })
    export class LoginModule {}

组件文件:login.component.ts

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

    @Component({
        selector: 'sc-auth-login',
        template: `
            <form (ngSubmit)="onSubmit(f)" #f="ngForm" novalidate>
            <input name="first" ngModel required #first="ngModel">
            <input name="last" ngModel>
            <button>Submit</button>
            </form>
            <p>First name value: {{ first.value }}</p>
            <p>First name valid: {{ first.valid }}</p>
            <p>Form value: {{ f.value | json }}</p>
            <p>Form valid: {{ f.valid }}</p>
        `,
    })
    export class LoginComponent {
        onSubmit(f: NgForm) {
        console.log(f.value);  // { first: '', last: '' }
        console.log(f.valid);  // false
    }
}

知道这有什么问题吗?

您必须提供名称给ngModel.so,以便可以创建局部变量。

<input name="first" [(ngModel)]="first" required #first="ngModel">
<input name="last" [(ngModel)]="last" #last="ngModel">

就我而言,我只是在输入字段中缺少ngModel指令

<input ngModel name="name" #name="ngModel">

通过添加解决了该问题。

暂无
暂无

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

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