如何在Angular 2中使用ngModel过滤空值



流量:

  1. 用户提交了一个包含一些数据的表单,一些用户没有填写的可选字段在mongo中保存为"null">
  2. 稍后,用户决定编辑该表单
  3. 服务获取表单并将其显示给用户
  4. 表单输入框显示为"null",因为在步骤1中他没有填写这些框

所以,我创建了一个管道:

import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'transformNull'
})
export class TransformNull implements PipeTransform {
transform(value) {
if (value == null) {
return null;
}
}

然后,在HTML中,我试图分解ngModel:

[ngModel]="user.extraInfo | transformNull" (ngModelChange)="user.extraInfo.value=$event"

这导致了这个错误:

Cannot set property 'value' of undefined TypeError: Cannot set property 'value' of undefined

我试图用*ngIf="isDataAvailable"延迟页面加载,错误消失了,用户可以保存表单,值被存储到mongo,但当他刷新页面时,输入框是空的。

然后我删除了*ngIf,添加了elvis运算符,但值错误又回来了。

我使用的是zone.js v0.7.4,尝试过0.7.2和0.7.5,但没有成功。

我在这里错过了什么?

对于ngModel,需要将其拆分为

[ngModel]="user?.extraInfo " (ngModelChange)="user.extraInfo = $event"

最新更新