我正在尝试登录表单,但无法解决此错误
Uncaught Error: Template parse errors:
Can't bind to 'formGroup' since it isn't a known property of 'form'. ("<form [ERROR ->][formGroup]="form" (ngSubmit)="onSubmit()">
<fieldset>
<legend>Login</legend>
"): ng:///AppModule/LoginComponent.html@0:6
我是Angular的新手,我完全不明白我的代码出了什么问题。
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<fieldset>
<legend>Login</legend>
<div class="form-field">
<label>Email:
<input name="username"
formControlName="username"
type="email">
</label>
</div>
<div class="form-field">
<label>Password:
<input name="password"
formControlName="password"
type="password">
</label>
</div>
</fieldset>
<div class="form-buttons">
<button class="button button-primary"
(click)="onSubmit()">Login
</button>
</div>
</form>
组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
form: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
error = '';
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService
) {
this.createForm();
}
ngOnInit() {
this.authenticationService.logout();
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
createForm() {
this.form = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
get f() {
return this.form.controls;
}
onSubmit() {
this.submitted = true;
if (this.form.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.pipe(first())
.subscribe(
() => {
this.router.navigate([this.returnUrl]);
},
error => {
this.error = error;
this.loading = false;
});
}
}
我在他们之前做了过一些表格,但没有遇到更大的问题。对我来说,最大的惊喜是我无法在互联网上找到该问题的解决方案。
答案 0 :(得分:1)
只需在BrowserModule之后导入ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
答案 1 :(得分:0)
您可能忘记了在ReactiveFormsModule
中导入AppModule
:
@NgModule({
imports: [
...
ReactiveFormsModule,
...
答案 2 :(得分:0)
同时导入模块FormsModule
和ReactiveFormsModule