【问题标题】:TS2564: Property 'signupForm' has no initializer and is not definitely assigned in the constructorTS2564:属性 'signupForm' 没有初始化程序,并且未在构造函数中明确分配
【发布时间】:2021-06-23 02:24:13
【问题描述】:

我正在使用 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') 注册表格:NgForm;

【问题讨论】:

标签: angular angular8


【解决方案1】:

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

tsconfig.json

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

【讨论】:

    【解决方案2】:

    你也可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 1970-01-01
      • 2021-04-13
      • 2021-05-21
      • 2021-05-06
      • 1970-01-01
      • 2021-09-04
      • 2021-08-14
      • 2021-02-28
      相关资源
      最近更新 更多