角度错误 TS2531:对象可能为“空" [英] Angular error TS2531: Object is possibly 'null'

查看:44
本文介绍了角度错误 TS2531:对象可能为“空"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个包含如下输入的 Component.html:

So I have a Component.html that includes an input as follows:

<input type="text" (change) = "setNewUserName($event.target.value)"/>

component.ts 是:

the component.ts is:

import { Component } from "@angular/core";
@Component({
    selector : 'app-users-list',
    templateUrl : './usersList.component.html'
})
export class UsersListComponent 
{
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

最后是module.ts:

and finally the module.ts is:

@NgModule ({
    declarations: [UsersListComponent],
    imports : [CommonModule],
    exports: [UsersListComponent]
})
export class UsersListModule {}

运行服务器时,弹出如下错误:

When running the server, the following error pops up:

error TS2531: Object is possibly 'null'.

1 <input type="text" (change) = "setNewUserName($event.target.value)"/>
                                                              ~~~~~

推荐答案

你在使用 Angular Ivy 吗?很可能是由于 模板类型检查常春藤AOT.

Are you using Angular Ivy? Most possibly it's due to the template type checking in Ivy AOT.

尽管如此,还是有多种选择

Nevertheless, there are multiple options

<input type="text" (change) = "setNewUserName($event)"/>

export class UsersListComponent {
   setNewUserName (event: any): void {
       console.log('setNewUserName', event.target.value)
   }
}

选项 2:使用模板引用变量

<input #userName type="text" (change) = "setNewUserName(userName.value)"/>

export class UsersListComponent {
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

选项 3:使用 $ 禁用类型检查any()

<input type="text" (change) = "setNewUserName($any($event.target).value)"/>

export class UsersListComponent {
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

选项 4:模板驱动或反应式形式

使用 模板驱动reactive 表单以获取输入值.IMO 这将是三者中最优雅的方法.

Option 4: Template-driven or reactive form

Use a template-driven or reactive form to get the input value. IMO this would be the most elegant approach of the three.

更新:添加禁用类型检查

这篇关于角度错误 TS2531:对象可能为“空"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆