首页 > 解决方案 > TS2564:属性 'signupForm' 没有初始化程序,并且未在构造函数中明确分配

问题描述

我正在使用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;

标签: angularangular8

解决方案


你也可以这样做:

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

对于!操作员,您基本上会说:我知道我在做什么,并且我知道 angular 会为我设置这个值。有关操作员的更多信息,请参阅此答案


推荐阅读