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

Angular报input标签未终止(-995002) 如何给日期输入框设当前日期默认值

报错原因

触发Opening tag "input" not terminated.ngtsc(-995002)编译错误的核心原因:

  • Angular属于纯前端框架,模板编译阶段仅识别原生HTML、Angular专属模板语法,完全不支持解析、执行服务端运行的PHP代码
  • 嵌入在value属性里的<?php echo date("Y-m-d");?>片段被Angular编译器识别为未闭合的HTML标签内容,判定input开标签未正常终止,直接抛出编译错误
  • 注意:PHP代码只能在服务端解析运行,无法直接嵌入Angular组件模板文件中生效,二者运行环境完全隔离。
正确实现方案

原生type="date"输入框仅支持YYYY-MM-DD格式的日期值作为默认值,Angular中可根据使用的表单模式选择对应实现:

1. 无表单/模板驱动表单场景

先在组件TS文件中生成格式化后的当前日期:

// 对应组件.ts文件
import { Component } from '@angular/core';

@Component({
  selector: 'app-date-demo',
  templateUrl: './date-demo.component.html'
})
export class DateDemoComponent {
  // 直接截取ISO日期的年月日部分,符合date输入框格式要求
  currentDate = new Date().toISOString().split('T')[0];
}

模板中通过属性绑定传入默认值即可:

<!-- 普通属性绑定 -->
<input type="date" class="form-control" [value]="currentDate">

<!-- 若使用ngModel双向绑定 -->
<input type="date" class="form-control" [(ngModel)]="currentDate">

2. 响应式表单场景

初始化表单控件时直接传入格式化后的当前日期作为默认值:

// 对应组件.ts文件
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-date-demo',
  templateUrl: './date-demo.component.html'
})
export class DateDemoComponent implements OnInit {
  dateForm: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    const currentDate = new Date().toISOString().split('T')[0];
    this.dateForm = this.fb.group({
      dateInput: [currentDate] // 配置默认值
    });
  }
}

模板中绑定对应表单控件:

<form [formGroup]="dateForm">
  <input type="date" class="form-control" formControlName="dateInput">
</form>

附报错参考截图:
Angular编译报错截图

避坑提示:不要给date类型输入框传入带时分秒、或本地化格式(如YYYY/MM/DD、MM-DD-YYYY)的日期值,会导致默认值无法正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:24:21