首页 > 解决方案 > 如何在Angular 7中处理修剪()和toLowerCase()的Null检查

问题描述

我在 Angular 7 中有一个输入字段,我使用 trim () 和 toLowerCase() 逻辑有效,但有时在控制台中显示 .trim() 和 toLowerCase() 未定义如何处理此错误请帮助。

             <input
             oninput="this.value = this.value.toLowerCase()"
             (blur)="supplierInfo.name = supplierInfo.name.trim()"
             [(ngModel)]="supplierInfo.name" 
              />

标签: angular

解决方案


您可以使用安全导航运算符 ( ? ) 进行空/未定义检查

例如:

(blur)="supplierInfo?.name = supplierInfo?.name?.trim()"

为 this.value 添加相同的内容

oninput="this.value = this.value?.toLowerCase()" - In this case, it the new value is null/undefined - then it will retain the same
oninput="this.value = this.value?.toLowerCase() || ''" - Will update the string to a blank string

推荐阅读