Angular 13 NgForm ViewChild issue



当前移动到Angular 13,并且此ViewChild和NgForm 存在一些问题

@ViewChild('txtForm', { read: NgForm }) form: NgForm;
.......
<form #txtForm="ngForm" (ngSubmit)="onSubmit(txtForm)">
<input name="first" ngModel required #first="ngModel">
<input name="last" ngModel>
<button type="submit">Submit</button>
</form>

对于这种语法,当构建时,我得到以下错误:

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

11   @ViewChild('txtForm', { read: NgForm }) form: NgForm;

如果我将类型更改为any,它可以工作,但为什么它与NgForm 有问题

据我所知,早期版本的没有问题

问题

这里的Angular版本没有问题。此错误是因为您的设置:

"strictPropertyInitialization": true

在这里,如果您在声明期间或consturator中都没有初始化属性,那么编译器将抛出一个错误。

解决方案

  1. 只需在设置文件(tsconfig.json(中设置上述属性的值即可。查看此处

  2. 您也可以使用类似以下语句的非null断言运算符(!(来消除此错误。查看此处

    @ViewChild('txtForm', { read: NgForm }) form!: NgForm;
    

这是因为角度cli严格模式

更多信息链接

你可以像这个一样在:之前添加!来解决你的问题

@ViewChild('txtForm', { read: NgForm }) form!: NgForm;

这个标志是干什么的?

这是非null断言运算符。这是一种告诉编译器";这个表达式在这里不能为null或undefined,所以不要抱怨它为null或未定义的可能性"有时,类型检查器本身无法做出该决定。

完整解释链接

最新更新