TS2564: 属性 'signupForm' 没有初始化器并且在构造函数中没有明确赋值

TS2564: Property 'signupForm' has no initializer and is not definitely assigned in the constructor

我正在使用 ViewChild 进行 angular 表单提交。这是我的代码,

app.component.ts

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    @ViewChild('f') signupForm: NgForm; 

    onSubmit(){
        console.log(this.signupForm);
    }
}

app.component.html

<form #f="ngForm" (ngSubmit)="onSubmit()" novalidate></form>

但是我收到了这个错误,

src/app/app.component.ts:11:21 - error TS2564: Property 'signupForm' has no initializer and is not definitely assigned in the constructor.

11 @ViewChild('f') signupForm: NgForm;

终于找到答案了。我必须在 tsconfig.json 中将 strictPropertyInitialization 标记为 false。添加这个因为有人提出了同样的问题会发现这很有用。 (您可能需要再次使用 ng serve

tsconfig.json

{
  "compilerOptions": {
    ...
    "strictPropertyInitialization": false
  }
}

您也可以这样做:

@ViewChild('f') signupForm!: NgForm; 

使用 ! 运算符,您基本上可以说:我知道我在做什么,我知道 angular 会为我设置这个值。有关运算符的详细信息,请参阅