我有一个角度路由,在其中一个组件中我有简单的登录表单,并在模板中提供formGroup,显示上面的错误。
步骤:在app模块中导入ReactiveFormsModule。
在路由组件中:
app.routingmodule.ts
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { CatalogViewComponent } from './views/catalog/catalog.component';
@NgModule({
declarations: [
LoginViewComponent, HomeViewComponent, CatalogViewComponent
],
imports: [
RouterModule.forRoot([
{ path: 'login', component: LoginViewComponent },
{ path: 'home', component: HomeViewComponent },
{ path: 'catalog', component: CatalogViewComponent },
{ path: '**', redirectTo: 'login' }
])
],
exports: [
RouterModule
],
providers: [],
})
export class AppRoutingModule {}
catalog.component.ts
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'reactiveform',
templateUrl: 'catalog.component.html',
})
export class CatalogViewComponent implements OnInit {
form: FormGroup;
constructor() {
}
ngOnInit() {
this.form = new FormGroup({
name: new FormControl(''),
userName: new FormControl('')
});
console.log(this.form);
}
processForm() {
console.log("formProcessing" + this.form.value);
}
}
catalog.component.html
<form [formGroup]="form" (ngSubmit)="processForm()" >
<div class="form-group">
<label for="name">Name </label>
<input type="text" class="form-control" name="name" formControlName="name" required>
</div>
<div class="form-group">
<label for="userName">Username </label>
<input type="text" class="form-control" name="userName" formControlName="userName" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Submit </button>
</div>
</form>
演示网址:
如果我在Html中删除formGroup,应用程序可以正常工作
答案 0 :(得分:5)
您在CatalogViewComponent
中声明了AppRoutingModule
,因此您必须在那里导入ReactiveFormsModule
:
<强> app.routing.module.ts 强>
@NgModule({
declarations: [
LoginViewComponent, HomeViewComponent, CatalogViewComponent
],
imports: [
ReactiveFormsModule, <=============================== add this
RouterModule.forRoot([
{ path: 'login', component: LoginViewComponent },
{ path: 'home', component: HomeViewComponent },
{ path: 'catalog', component: CatalogViewComponent },
{ path: '**', redirectTo: 'login' }
])
],
exports: [
RouterModule
],
providers: [],
})
export class AppRoutingModule {}
<强> Forker Stackblitz 强>
另见
另一种方法是创建SharedModule:
@NgModule({
...
exports: [
ReactiveFormsModule
]
})
export class SharedModule {}
将其导入任何使用反应形式的模块