html - Angular 错误 TS2531 : Object is possibly 'null'

标签 html angularjs angular typescript

所以我有一个 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 吗?很可能是由于 template type checking在 Ivy AOT。
然而,有多种选择
选项 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:模板驱动或响应式(Reactive)形式
使用 template-drivenreactive表单以获取输入值。 IMO 这将是三者中最优雅的方法。
更新:添加 disable type checking

关于html - Angular 错误 TS2531 : Object is possibly 'null' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67123603/

相关文章:

jquery - 多步进度条更改输入字段中回车键的状态

javascript - 在 Angular-UI 日历/全日历中禁用事件大小调整

javascript - 选择 AngularJS 中智能表的所有复选框

css - 如何访问动态嵌套结构中最后一个元素的样式属性?

angular - 如何使用 provideIn : 'platform' in angular 9

html - wordpress:添加 <noscript> 标签会使 <head> 标签自动关闭

html - 跨浏览器嵌入式视频灰度过滤器

angularjs - 什么是抽象 :true do in ui-router?

html - HTML5 电子邮件验证和 angular2 一起工作吗?

python - 根据数据库正确验证 HTML POST