Angular login.component.html 中的表单未向 login.component.ts 发送数据

Angular form in login.component.html not sending data to login.component.ts

我有一个带有电子邮件和密码的简单登录表单,当我尝试将数据发送到 login.components.ts 时,表单是空的

login.component.html:

    <mat-spinner *ngIf="isLoading"></mat-spinner>
    <form *ngIf="!isLoading" #loginForm="ngForm" (ngSubmit)="login(loginForm)">
        <mat-form-field appearance="fill" class="login-full-width">
          <mat-label>Enter your email</mat-label>
          <input matInput [formControl]="email" type="email" name="email" placeholder="E-Mail" required>
          <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
        </mat-form-field>
        <mat-form-field appearance="fill" class="login-full-width">
            <mat-label>Enter your password</mat-label>
            <input matInput [formControl]="password" name="password" [type]="hide ? 'password' : 'text'" required>
            <button mat-icon-button matSuffix (click)="hide = !hide" [attr.aria-label]="'Hide password'" [attr.aria-pressed]="hide">
              <mat-icon>{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
            </button>
        </mat-form-field>
        <button mat-raised-button color="primary" type="submit">Login</button>
    </form>
</mat-card>

login.component.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, NgForm, NgModel, Validators } from '@angular/forms';
import { response } from 'express';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

    constructor(private http: HttpClient) {  }

    ngOnInit(): void {
    }

    email = new FormControl('', [Validators.required, Validators.email]);
    password = new FormControl('', [Validators.required]);
    hide = true;
    isLoading = false;
    httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    }


    login(form: NgForm) {      
      console.log(form.value); <=========================== this is empty
      this.http.post<{message: string}>('http://localhost:3000/login', form.value, this.httpOptions)
        .subscribe((responseData) => {
          console.log(responseData.message);
        })
    }

    getErrorMessage() {
        if (this.email.hasError('required')) {
            return 'You must enter a value';
        }

        return this.email.hasError('email') ? 'Not a valid email' : '';
    }
}

Console log is giving empty object

“来自 express.js 的问候”来自后端,它工作正常(甚至用邮递员测试过)

我认为您将 template-driven 形式与反应形式组合在一起是错误的。

我建议使用一种方法从中获取数据。

示例 [formControl] 是一个反应式表单项,您正在通过 template-driven 表单提交表单。他们不一起工作。