【发布时间】:2021-04-06 15:37:13
【问题描述】:
我正在尝试在 Angular 中创建一个非常基本的表单(现在是一个标签和一个输入字段)。我知道这个问题在这里被问了很多次,但是尽管导入了 FormsModule 和 ReactiveFormsModule,我仍然遇到这个错误,正如 Stackoverflow 上多次建议的那样。
我的 html(我也尝试使用
<form class="form" [formGroup]="form" (ngSubmit)="onSubmit()">
<!--formgroup topic-->
<div class="form-group">
<label for="topic">Topic:</label>
<br />
<input type="text" id="topic"
formControlName="topic" required
placeholder="Write something here..."
class="form-control" />
</div>
</form>
我的模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { AddTicketComponent } from './add-ticket/add-ticket.component';
import { SettingsComponent } from './settings/settings.component';
import { OverviewComponent } from './overview/overview.component';
import { HistoryComponent } from './history/history.component';
import { RouterModule } from '@angular/router';
import { AppRoutingModule } from '../app-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatTableModule } from '@angular/material/table';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [
AddTicketComponent,
SettingsComponent,
OverviewComponent,
HistoryComponent
],
imports: [
CommonModule,
FontAwesomeModule,
RouterModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule,
MatTableModule,
BrowserModule
]
})
export class TicketToolModule { }
我的组件:
import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Ticket } from '../Data/Models/ticket';
@Component({
selector: 'app-history',
templateUrl: './history.component.html',
styleUrls: ['./history.component.css'],
})
export class HistoryComponent implements OnInit {
public form: FormGroup = new FormGroup({
id: new FormControl('', Validators.required),
topic: new FormControl('', Validators.required),
category: new FormControl('', Validators.required),
subcategory: new FormControl('', Validators.required),
impact: new FormControl('', Validators.required),
description: new FormControl('', Validators.required),
date: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
images: new FormControl('', Validators.required)
});
constructor() {
}
ngOnInit(): void {
this.form = new FormGroup({});
}
}
我使用的是 Angular 11.2.8 版。
这是 Stackblitz 上错误的打印屏幕: https://i.stack.imgur.com/teoyi.png
解决方案 我在另一个模块中工作,即使我使用 CLI 创建了这个模块,它也没有被导入到 AppModule。导入后,所有错误都消失了。所以,如果你的项目中有各种奇怪的错误,请检查你的模块是否已经导入到 AppModule 中!
【问题讨论】:
标签: angular forms formgroups