从 Angular 中的材料日期选择器中设置特定日期的样式 [英] Stylizing specific days from the material datepicker in Angular

查看:20
本文介绍了从 Angular 中的材料日期选择器中设置特定日期的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在 datepicker 对象中设置特定日期的样式,但我似乎无法从日历访问 DOM 元素.我尝试使用视图子项,但这只能让我访问选择器元素,而不是单击选择器时创建的日历.

Im looking to style specific days in the datepicker object but I cant seem to get access to the DOM elements from the calendar. I tried using a view child, but that only gave me access to the picker element, not the calendar that gets created when click on the picker.

我还尝试向日期选择器添加面板类并尝试对其进行选择,但它似乎也不起作用.https://stackblitz.com/编辑/angular-zjt5wz-ehdbdt?file=app/datepicker-start-view-example.ts

I have also tried adding a panel class to the date picker and trying to select on that, but it also doesnt seem to work. https://stackblitz.com/edit/angular-zjt5wz-ehdbdt?file=app/datepicker-start-view-example.ts

理想情况下,我希望每天都应用一个符合特定标准的课程.例如,将所选日期之前的所有日子设置为黄色.我该怎么做?

Ideally, I want to apply a class to every day that meets a specific criteria. For example, style all days prior to the selected day as yellow. How can I go about doing this?

推荐答案

那是因为当 opened 事件触发时,视图还不包含日历的 DOM 元素.

That's because when the opened event fires, the view does not contain the DOM elements for the calendar yet.

您可以将代码包装在 setTimeout 中作为解决方法

You can wrap your code in a setTimeout as a workaround

streamOpened(event) {
   setTimeout(()=>{
   let elements = document.querySelectorAll('.endDate');
   //here elements will not be empty
   });

修改后的stackblitz

编辑

根据您的评论,材料日期选择器 API 没有用于侦听显示日期范围更改的事件.作为黑客,您可以尝试像这样手动收听下一个/上一个按钮点击

Following your comment, the material datepicker API has no event for listening to changes to displayed date range. As a hack, you could try manually listening to next/previous button click like this

constructor(private   renderer:Renderer2){}
//...
let nextBtn = document.querySelectorAll('.mat-calendar-next-button')[0];
this.renderer.listen(nextBtn, 'click', ()=>
{
  console.log('click on next')
  //Re-run logic here (probably in timeout again...)
})

编辑 2

在您的第二条评论之后,这是一个将刷新绑定到所有日历按钮点击的示例.这应该足以让你继续前进.不过,您可能需要为其他日历事件添加更多侦听器

Following your 2nd comment, here is an example that binds refresh to all calendar button clicks. That should be enough to get you going. You'll probably need to add more listener to other calendar events though

更新演示

基本上可以尝试监听所有的点击事件

Basically, you can try listening to all click events

let x =  elements[0].querySelectorAll('.mat-calendar-body-cell');
    x.forEach(y => {

      let c = new Date(y.getAttribute("aria-label"));
      if(c < this.startDate)
      {
        y.classList.add('newClass');
      } 
    });

这篇关于从 Angular 中的材料日期选择器中设置特定日期的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆