【发布时间】: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;
【问题讨论】:
-
我尝试添加这样的构造函数,但没有奏效:(
-
你使用的是什么版本的 TypeScript? Strict Class Initialization
-
看起来像是在一个简单的堆栈闪电战中工作:stackblitz.com/edit/…(检查您是否在模块中导入 FormsModule 或尝试使用
@ViewChild('f') signupForm: NgForm=null; -
我在
app.module.ts中添加了FormsModule,现在也尝试了@ViewChild('f') signupForm: NgForm=null;,但不幸的是没有用:'(