【发布时间】:2018-08-30 21:42:12
【问题描述】:
我正在研究 Angular 5 Reactive Forms: 我有这个错误: 没有将“exportAs”设置为“ngModel”的指令 我在其他论坛上看到这个问题可能有很多原因: HTML 模板拼写错误,忘记导入“FormsModule”或“ReactiveFormsModule”,....
我检查了我的代码,但没有发现问题 你能帮我吗 !!!
控制台错误:
There is no directive with "exportAs" set to "ngModel" ("
[(ngModel)]="user.FirstName"
formControlName="FirstName"
[ERROR ->]#FirstName="ngModel" />
<label for="firstName">{{ 'FIRST_NAME' | translate:param}}</label>")
: ng:///AppModule/LoginComponent.html@12:15
app.module.ts:
//angular moudel
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
....
@NgModule({
declarations: [
.....
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
...
AppRoutingMoudel,
],
...
})
LoginComponent.ts
import { Component, OnInit } from '@angular/core';
import { User } from './../../../model/user';
import {FormBuilder,FormGroup,FormControl,Validators,NgForm} from '@angular/forms'
....
export class LoginComponent implements OnInit {
user : User;
userLoginForm: FormGroup;
constructor(private userLoginFormBuilder:FormBuilder) {
this.user = new User ("TestName", "Yagmi",
"TestName@Yagmi.com", "esay", "esay");
this.userLoginForm = this.userLoginFormBuilder.group({
FirstName: new FormControl (this.user.FirstName,
[Validators.minLength(4),])
});
}
}
LoginComponent.Html
<form class="col s12" [formGroup]="userLoginForm" (ngSubmit)="saveUserLogin()">
<div class="row">
<div class="input-field col s12 m6">
<input id="firstName"
type="text"
class="validate"
[(ngModel)]="user.FirstName"
formControlName="FirstName"
#FirstName="ngModel" />
<label for="firstName">{{ 'FIRST_NAME' | translate:param }}</label>
<p class="data-error data-validation" *ngIf="FirstName.errors?.minlength">
min length is 4 caracters.
</p>
<p class="data-error data-validation" *ngIf="FirstName?.touched">
touched.
</p>
</div>
</div>
</form>
user.ts
export class User {
constructor(
public FirstName: string,
public LastName: string,
public Email: string,
public Passeword: string,
public ConfirmPasseword: string
)
}
【问题讨论】:
-
你能附上你的用户模型定义吗?
-
为什么要同时使用模板驱动和反应式表单,我建议你选择。
-
你能告诉我我必须删除什么才能只使用反应形式
-
谢谢 Alex,我明白我的错误在哪里了
标签: javascript angular typescript