Angular 错误 TS2531:对象可能是 'null'

Angular error TS2531: Object is possibly 'null'

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

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

component.ts 是:

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 是:

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

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

error TS2531: Object is possibly 'null'.

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

您在使用 Angular Ivy 吗?很可能是由于 Ivy AOT 中的 template type checking

然而,有多种选择

选项 1:将事件作为参数发送

<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:模板驱动或反应形式

使用template-driven or reactive形式获取输入值。 IMO 这将是最优雅的方法。

更新: 添加disable type checking

试试这个

setNewUserName($any($event.target).value);

它会起作用

这对我有用

($any($event.target).value);

角度 13