【发布时间】:2022-02-10 05:41:48
【问题描述】:
我尝试在我的 Angular 项目中使用 formGroup,但它返回错误:
无法绑定到“formGroup”,因为它不是“form”的已知属性。
我已将 FormsModule 和 ReactiveFormsModule 导入到我的 auth.module 和 app.module 中,但我似乎无法解决我的错误。我希望有人能好心地帮助我,拜托。
HTML
<form [formGroup]="form" (submit)="submit()">
<div class="input-field">
<input id="username" formControlName="username" type="text" required>
<label for="username">Username</label>
</div>
<div class="input-field">
<input id="email" formControlName="email" type="text" required>
<label for="email">Email</label>
</div>
<div class="input-field">
<input id="password" formControlName="password" type="password" required>
<label for="password">Mot de passe</label>
</div>
<div class="button-form">
<button class="custom-btn btn-sign-in" type="submit">S'inscire</button>
</div>
</form>
auth.module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
LoginComponent,
RegisterComponent
],
imports: [
CommonModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
})
export class AuthModule { }
app.module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MainComponent } from './pages/main/main.component';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
routingComponents,
MainComponent
],
imports: [
CommonModule,
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
register.component
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
import { Router } from '@angular/router';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
form: FormGroup;
constructor(
private router: Router,
private formBuilder: FormBuilder
) { }
ngOnInit(): void {
this.form = this.formBuilder.group({
username: '',
email: '',
password: ''
});
}
submit(): void{
console.log(this.form.getRawValue());
}
btnClick() {
this.router.navigate(['/login']);
}
}
【问题讨论】:
-
对我来说看起来不错。尝试重新启动服务器。可能听起来很傻,但在很多情况下都帮助了我。
-
@AakashGoplani 我已经尝试重新启动服务器但它没有改变任何东西,我的错误仍然存在;(
-
您能否分享整个错误描述,包括路径?
-
这个 AuthModule 是从哪里加载的。我在 AppModule 中没有看到任何条目!
-
@AakashGoplani 非常感谢你解决了我的问题!
标签: javascript html angular typescript