Angular自动补全组件如何过滤Name为空的记录
解决Angular自动补全过滤结果包含空Name记录的问题
你的当前filter逻辑仅做了关键词匹配,未排除Name为空的记录,只需在过滤条件中增加对Name字段的非空校验即可。
修改前的filter函数:
filter(value = '') { if (typeof value !== 'string' || typeof value === 'undefined' || typeof this.chatList==='undefined') { return; } this.filteredObject = this.chatList.filter( a => ~a.Name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase())) ); }
修改后的filter函数:
filter(value = '') { if (typeof value !== 'string' || typeof value === 'undefined' || typeof this.chatList === 'undefined') { return; } this.filteredObject = this.chatList.filter(a => { // 先排除Name为空、undefined、null的情况 if (!a.Name) return false; // 再执行原有的关键词匹配逻辑 return a.Name.toLocaleLowerCase().includes(value.toLocaleLowerCase()); }); }
说明:
- 新增
!a.Name判断,直接排除Name为空字符串、undefined或null的记录 - 把原有的
~indexOf替换成更直观的includes方法,功能完全一致但可读性更好 - 保留原有边界条件判断,避免
this.chatList未定义或value类型错误导致的异常
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

