表单不起作用,formGroup 有问题

Form doesn't work, problem with formGroup

我正在尝试登录表单,但无法修复此错误

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;
          });
  }
}

我在他们之前做了一些表格,但没有遇到更大的问题。对我来说最大的惊喜是我无法在互联网上找到这个问题的解决方案。

您可能忘记在 AppModule 中导入 ReactiveFormsModule:

@NgModule({
  imports: [
    ...
    ReactiveFormsModule,
    ...

同时导入模块 FormsModuleReactiveFormsModule

只需在 BrowserModule 之后导入 ReactiveFormsModule

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }