我从这里开始做例: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
}
}
知道它有什么问题吗?
答案 0 :(得分:0)
您必须为ngModel.so提供名称,即可以创建局部变量。
<input name="first" [(ngModel)]="first" required #first="ngModel">
<input name="last" [(ngModel)]="last" #last="ngModel">
答案 1 :(得分:0)
就我而言,我只是缺少输入字段的 ngModel 指令
<input ngModel name="name" #name="ngModel">
通过添加它来解决问题。