所以我有一个 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-driven或 reactive表单以获取输入值。 IMO 这将是三者中最优雅的方法。
更新:添加 disable type checking
关于html - Angular 错误 TS2531 : Object is possibly 'null' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67123603/