我尝试导入FormsModule和NgForm模块,以及将FormsModule添加到imports数组。
下面是我的代码:
//our root app component
import { Component, NgModule, VERSION } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule, NgForm} from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form #searchForm="ngForm">
<input type="text" required [(ngModel)]="model.search" ngControl="search" #inputSearch="ngForm">
<p class="error" [hidden]="inputSearch.valid"> This input is required</p>
</form>
`,
styles: [`
.error {
color: red;
font-size: 11px;
}
`]
})
export class App {
public model = {
search: ""
}
constructor() {
}
}
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [App],
bootstrap: [App],
})
export class AppModule {}
下面是一个错误打印输出:
runtime.9ff156e16d788666a54a.js:16错误:模板解析错误:
没有将“ exportAs”设置为“ ngForm”的指令(“]#searchForm =” ngForm“>]#inputSearch =” ngForm“>此输入为必填”):
ng:///AppModule/App.html@2:76无法绑定到“ ngModel”,因为它不是
“输入”的已知属性。 (“] [(ngModel)] =” model.search“
ngControl =“ search”#inputSearch =“ ngForm”> https://run.plnkr.co/rhpwnL6UIQwCFOKZ/src/main.js加载
https://run.plnkr.co/rhpwnL6UIQwCFOKZ/src/main.js f @
runtime.9ff156e16d788666a54a.js:16
最佳答案
该错误是由以下行引起的:
#inputSearch="ngForm"
这是正确的行:
#inputSearch="ngModel"
这是工作示例。当您在form标记内使用ngModel时,还需要为“ name”属性提供值。
<form #searchForm="ngForm">
<input type="text" required name="search" [(ngModel)]="model.search" #inputSearch="ngModel">
<p class="error" [hidden]="inputSearch.valid"> This input is required</p>
</form>