You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular表单中传递createdDt、updatedDt值且不在模板中显示?

Angular表单隐藏日期字段实现方案

实现步骤

  • 为createdDt和updatedDt创建FormControl,初始化值为当前日期时间,若不需要手动编辑可设置禁用状态
  • 无需在模板中添加对应控件,提交时直接传递字段值
  • 若设置了禁用,提交时需用getRawValue()获取完整表单值(包含禁用控件)

修正后的代码

ngOnInit(): void {
  // 获取当前日期时间,可根据后端要求调整格式(如直接传Date对象或转为特定字符串)
  const currentDateTime = new Date().toISOString();

  this.addMessageForm = this.formBuilder.group({
    'messageTitle': new FormControl(''),
    'messageDec': new FormControl(''),
    'messageSentBy': new FormControl(''),
    // 设置初始值并禁用,避免被修改
    'createdDt': new FormControl({ value: currentDateTime, disabled: true }),
    'updateDt': new FormControl({ value: currentDateTime, disabled: true })
  });

  // 提交时用getRawValue()获取所有字段(包括禁用的)
  createMessage(this.addMessageForm.getRawValue()).subscribe(
    () => console.log("Message Created Successfully"),
    () => console.log("Message Failed to Create")
  );
}

补充说明

  • 若后端接受原生Date对象,直接将currentDateTime设为new Date()即可
  • 若后续需要在代码中修改这两个字段值,可去掉disabled: true,提交时用this.addMessageForm.value获取值
  • 因为是隐藏字段,模板中无需添加任何对应输入控件,表单提交时会自动携带初始值

内容的提问来源于stack exchange,提问作者JSLover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 11:54:32