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

如何在选择日期后隐藏MatDatepicker Toggle图标并显示新图标

实现方案

修正代码并添加状态控制

先把你代码里的<inpu>改为<input>,然后通过双向绑定跟踪选中日期,用*ngIf控制两个图标的显示切换:

<mat-radio-button value="1">Daily Consumption</mat-radio-button>
<input matInput class="date-input" [matDatepicker]="picker1" [(ngModel)]="selectedDate" readonly='true' required />
<!-- 未选日期时显示的选择按钮 -->
<mat-datepicker-toggle *ngIf="!selectedDate" matSuffix [for]="picker1">
  <mat-label matDatepickerToggleIcon>Select Date</mat-label>
</mat-datepicker-toggle>
<!-- 选中日期后显示的图标 -->
<mat-icon *ngIf="selectedDate" matSuffix (click)="picker1.open()">calendar_today</mat-icon>
<mat-datepicker #picker1></mat-datepicker>

组件类添加变量

在对应组件的TS文件里声明selectedDate变量,用来记录选中的日期:

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

@Component({
  // 保留你的组件元数据(selector、templateUrl等)
})
export class YourComponent {
  selectedDate: Date | null = null;
}

逻辑说明

  • 初始状态下selectedDate为null,显示原来的日期选择Toggle,点击可打开日期选择器。
  • 选中日期后,selectedDate会自动赋值,此时原Toggle隐藏,显示指定的Material图标(示例用calendar_today,可根据需求替换成其他图标)。
  • 新图标绑定了点击事件,用户点击能重新打开日期选择器,方便修改日期;如果不需要编辑功能,去掉(click)="picker1.open()"即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:35:30