【问题标题】:FormControl - empty string to nullFormControl - 空字符串为空
【发布时间】:2020-10-01 01:32:46
【问题描述】:

是否有可能将空字符串(等于“”)转换为null?

我有一个输入字段来覆盖数据库中的值。如果我在那里更改值,它将存储在数据库中 - 这很棒。但是,如果我再次编辑值(输入字段)并从中删除文本,它会向数据库发送一个空字符串(例如“”)。但它应该发送null 以显示源值。

app.component.ts

  readonly titleCtrl = new FormControl()
  readonly descriptionCtrl = new FormControl()
  readonly ageCtrl = new FormControl()

  readonly formGroup = new FormGroup({
    title: this.titleCtrl,
    description: this.descriptionCtrl,
    age: this.ageCtrl,
  })


private fillForm(item: Item): void {
  this.formGroup.setValue(
    {
      title: item.title.overrideValue,
      description: item.description.overrideValue,
      age: item.age.overrideValue,
    },
    { emitEvent: false },
  )
}

所以我想要达到的是,如果我在 title 中更改某些内容,然后再次删除它,它应该是 null 而不是 ""。

valueChanges 有什么可能吗?

【问题讨论】:

  • 看看这个问题和答案,这和你想要达到的目标一样吗?提出问题的人使用指令提出解决方案。 stackoverflow.com/questions/57902512/… 同样,其他答案讨论了不使用指令的不同方法

标签: angular forms angular8 formgroups


【解决方案1】:
sanitizeDataBeforeSendToServer(): void {
    const control = this.form.get('nameControl');    
    
    if ((control.value as string)?.trim() === '') {
        control.setValue(null);
    }
}
    
save(): void {
    this.sanitizeDataBeforeSendToServer();
    ....
}

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 2014-11-12
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    相关资源
    最近更新 更多