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

如何在Angular中生成含当年所有日期的表单?

动态生成全年日历表单的实现方案(Angular)

1. 动态构建表单控件

硬编码365个控件效率极低,我们可以通过遍历当年所有日期,自动生成对应的FormControl:

createCalendarForm() {
  const formControls: { [key: string]: any } = {};
  const currentYear = new Date().getFullYear();
  const startDate = new Date(currentYear, 0, 1);
  const endDate = new Date(currentYear, 11, 31);

  let currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    // 用`YYYY-MM-DD`格式作为控件名,既避免重复又清晰易读
    const dateKey = currentDate.toISOString().split('T')[0];
    formControls[dateKey] = ['']; // 初始值设为空
    currentDate.setDate(currentDate.getDate() + 1);
  }

  this.calendarForm = this.formBuilder.group(formControls);
}

2. 按月份分组日期数据

为了贴合日历的视觉结构,需要把全年日期按月份分组,方便后续HTML模板渲染:

calendarMonths: { monthName: string, dates: string[] }[] = [];

ngOnInit() {
  this.createCalendarForm();
  this.groupDatesByMonth();
}

groupDatesByMonth() {
  const currentYear = new Date().getFullYear();
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
  
  this.calendarMonths = monthNames.map((monthName, monthIndex) => {
    const dates: string[] = [];
    // 获取当月的总天数
    const daysInMonth = new Date(currentYear, monthIndex + 1, 0).getDate();
    
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(currentYear, monthIndex, day);
      dates.push(date.toISOString().split('T')[0]);
    }
    
    return { monthName, dates };
  });
}

3. 渲染日历样式的表单

通过嵌套循环遍历月份和日期,结合CSS网格布局实现类似日历的视觉结构:

<form [formGroup]="calendarForm" (ngSubmit)="onSubmitCalendar()">
  <div class="calendar-container">
    <div>Room type 1</div>
    
    <!-- 遍历每个月份区块 -->
    <div class="month-section" *ngFor="let month of calendarMonths">
      <h3>{{ month.monthName }}</h3>
      <!-- 日期网格布局 -->
      <div class="days-grid">
        <!-- 星期表头 -->
        <div class="day-header">日</div>
        <div class="day-header">一</div>
        <div class="day-header">二</div>
        <div class="day-header">三</div>
        <div class="day-header">四</div>
        <div class="day-header">五</div>
        <div class="day-header">六</div>
        
        <!-- 填充当月第一天前的空白格子 -->
        <div *ngFor="let _ of getLeadingBlanks(month.dates[0])" class="blank-day"></div>
        
        <!-- 遍历当月每一天 -->
        <div class="day-cell" *ngFor="let dateKey of month.dates">
          <span class="day-number">{{ getDayNumber(dateKey) }}</span>
          <input matInput formControlName="{{ dateKey }}" class="day-input">
        </div>
      </div>
    </div>
    
    <button style="font-size: large;" mat-button type="submit">{{ "Home.save" | translate }}</button>
  </div>
</form>

4. 辅助方法与样式补充

添加两个辅助方法处理日历布局细节,再用CSS完善样式:

// 计算当月第一天前需要填充的空白格子数量
getLeadingBlanks(firstDateKey: string): number[] {
  const firstDate = new Date(firstDateKey);
  const dayOfWeek = firstDate.getDay(); // 0代表周日,6代表周六
  return Array(dayOfWeek).fill(0);
}

// 提取日期中的日数(如2024-01-05返回5)
getDayNumber(dateKey: string): number {
  return new Date(dateKey).getDate();
}
.calendar-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.month-section {
  margin-bottom: 30px;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.day-header {
  text-align: center;
  font-weight: bold;
  padding: 8px;
  background-color: #f0f0f0;
}

.day-cell {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

.day-number {
  display: block;
  font-size: 14px;
  margin-bottom: 4px;
}

.day-input {
  width: 100%;
  box-sizing: border-box;
  text-align: center;
}

.blank-day {
  border: none;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:55:18