表单不起作用,formGroup的问题

问题描述 投票:0回答:3

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

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

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

angular forms login
3个回答
2
投票

只需在BrowserModule之后导入ReactiveFormsModule

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

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

1
投票

导入模块FormsModuleReactiveFormsModule


1
投票

你可能忘了在ReactiveFormsModule中导入AppModule

@NgModule({
  imports: [
    ...
    ReactiveFormsModule,
    ...
© www.soinside.com 2019 - 2024. All rights reserved.