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

Angular 8中如何根据年份选择动态显示/禁用半年选项

实现年份与半年下拉框的动态启用逻辑

UI中有年份和半年两个下拉框,需实现以下逻辑:

  1. 选中2021、2022、2023这类已结束的年份时,显示并启用H1(1-6月)和H2(7-12月)两个选项;
  2. 选中2024、2025这类未结束的未来年份时,H1(1-6月)需在当年7月及以后才启用,H2(7-12月)需在次年1月及以后才启用。

预期效果:

2022 显示选项1 H1(1-6月) 和 选项2 H2(7-12月)
2023 显示选项1 H1(1-6月) 和 选项2 H2(7-12月)
2024 当年7月开始后启用选项1 H1(1-6月),2025年1月开始后启用选项2 H2(7-12月)
以此类推....

修改后的代码实现

HTML模板

<mat-select [(value)]="selectedYear" placeholder="Select Year">
  <mat-option *ngFor="let year of years" [value]="year">
    {{year}}
  </mat-option>
</mat-select>

<mat-select class="lineDet subfamilySelect lossSubMatCls" placeholder="Select half Year">
  <mat-option 
    *ngFor="let type of halfYearlyOptions" 
    [value]="type"
    [disabled]="isHalfYearDisabled(type)">
    {{type}}
  </mat-option>
</mat-select>

组件代码

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements OnInit {
  years: number[] = [];
  halfYearlyOptions = ['H1 1-6月', 'H2 7-12月'];
  selectedYear?: number;
  currentDate = new Date();

  ngOnInit(){
    const now = new Date();
    // 生成2020年到当前年份+1的年份列表(包含未来年份)
    for (let year = 2020; year <= now.getFullYear() + 1; year++) {
      this.years.push(year);
    }
    // 默认选中当前年份
    this.selectedYear = now.getFullYear();
  }

  isHalfYearDisabled(halfYear: string): boolean {
    if (!this.selectedYear) return true;

    // 已完成的年份(小于当前年份):全部启用
    if (this.selectedYear < this.currentDate.getFullYear()) {
      return false;
    }

    // 处理当前/未来年份的选项禁用逻辑
    if (halfYear === 'H1 1-6月') {
      // 当年7月1日之后,H1周期结束,允许选择
      const h1AvailableDate = new Date(this.selectedYear, 6, 1);
      return h1AvailableDate > this.currentDate;
    } else if (halfYear === 'H2 7-12月') {
      // 次年1月1日之后,H2周期结束,允许选择
      const h2AvailableDate = new Date(this.selectedYear + 1, 0, 1);
      return h2AvailableDate > this.currentDate;
    }

    return true;
  }
}

逻辑说明

  1. 年份列表生成:扩展年份范围到当前年份+1,确保包含未来年份选项
  2. 选中年份绑定:通过selectedYear双向绑定年份下拉框的选中值
  3. 动态禁用判断:
    • 选中年份早于当前年份时,两个半年选项都启用
    • 选中当前或未来年份时:
      • H1选项:判断当前日期是否已过选中年份的7月1日,未过则禁用
      • H2选项:判断当前日期是否已过选中年份的次年1月1日,未过则禁用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 07:20:12