TS2564:属性“signupForm”没有初始值设定项,并且未在构造函数中明确分配

时间:2021-03-26 09:04:49

标签: angular angular8

我使用 ViewChild 进行角度表单提交。这是我的代码,

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 - 错误 TS2564:属性“signupForm” 没有初始化器,也没有在构造器中明确赋值。

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

2 个答案:

答案 0 :(得分:3)

你也可以这样做:

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

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

答案 1 :(得分:1)

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

tsconfig.json

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