如何在Angular Material日期选择器中突出显示自定义的月份和年份? [英] How to highlight custom months and years in Angular Material datepicker?

查看:60
本文介绍了如何在Angular Material日期选择器中突出显示自定义的月份和年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多天,可以是任何一年.我正在尝试自定义Angular Material日期选择器,以根据天的阵列突出显示几个月选择视图中的某些月份,以及某些年份显示在年份中的视图.

.html

 < input [matDatepicker] ="picker"/>< i class ="fas fa-chevron-down"</i>< mat-datepicker#picker></mat-datepicker> 

.ts

  arrayOfDays = [新日期('2019-01-01'),新日期('2020-08-10'),新日期('2020-09-20')]; 

我要实现的目标是在年视图中突出显示2019和2020 ,并且如果选择了2019,则突出显示月份JAN ,并且如果是2020被选中,然后突出显示MAY&.红色边框中为AUG (除了当前月份和年份,如下图所示).

这可能吗?

我进行了很多搜索,并尝试使用dateClass,(yearSelected)事件等,但是它不适用于月份和年份.

FYI- https://stackblitz.com/edit/angular-date-class-filter-aactjv 这是我发现的将自定义设计设置为日期视图的方法.但是我想要对Year和Months视图进行类似的实现.预先感谢..

解决方案

控制材料角度日期选择器事件确实有点复杂.我不知道是否有更好的方法,但是您可以使用自定义标头组件来获得它,请参见此

将dataService注入ExampleHeader和组件中后,Example头中是一个复杂的函数,但仅是写入

 构造函数(_intl:MatDatepickerIntl,@Inject(forwardRef(()=> MatCalendar))日历:MatCalendar< any> ;,@Optional()_dateAdapter:DateAdapter< any> ;,@Optional()@Inject(MAT_DATE_FORMATS)_dateFormats:MatDateFormats,changeDetectorRef:ChangeDetectorRef,私有dataService:DataService){超级(_intl,calendar,_dateAdapter,_dateFormats,changeDetectorRef)} 

在处理用户单击期间标签时,用户单击上一个按钮,然后单击下一个按钮以调用服务

  currentPeriodClicked():void {this.calendar.currentView =this.calendar.currentView ==月"?多年":月";this.dataService.displayMonth(this.calendar.activeDate.getFullYear(),this.calendar.currentView);}customPrev():void {this.previousClicked();this.dataService.displayMonth(this.calendar.activeDate.getFullYear(),this.calendar.currentView);}customNext():无效{this.nextClicked();this.dataService.displayMonth(this.calendar.activeDate.getFullYear(),this.calendar.currentView);} 

还需要在year中进行选择.

  yearSelected(event:any){this.dataService.displayMonth(event.getFullYear(),this.calendar.currentView);} 

您可以在中看到stackblitz

更新,如果只想备注";几个月来,事情变得更简单了,因为我们只需要控制(yearSelected)事件,所以我们就可以省去自定义标头了.

 < mat-datepicker #picker [dateClass] ="dateClass"(yearSelected)="yearSelected($ event)"[calendarHeaderComponent] ="exampleHeader".</mat-datepicker>months = [0,3]//<-在变量中我们要说明的月份yearSelected(event:any){setTimeout(()=> {let elements = document.querySelectorAll(.mat-calendar-content");令x = elements [0] .querySelectorAll(.mat-calendar-body-cell-content");x.forEach((y:any,month:number)=> {如果(this.months.indexOf(month)> == 0){{y.style ["border-color"] ="red";}}});})} 

请参见 stackblitz

I have an array of days, which can be from any year. I'm trying to customize Angular Material datepicker to highlight some months in months selection view, and also some years in year selection view based on the array of days.

.html

<input [matDatepicker]="picker" />
<i class="fas fa-chevron-down"></i>
<mat-datepicker #picker></mat-datepicker>

.ts

arrayOfDays = [new Date('2019-01-01'), new Date('2020-08-10'),  new Date('2020-09-20')];

What I'm trying to achieve is to highlight 2019 and 2020 in year view, and if 2019 is selected, then highlight month JAN and if 2020 is selected, then highlight MAY & AUG in Red border except for current month and year like the below images.

Is this possible?

I searched a lot and tried with dateClass, (yearSelected) event, etc but it is not applying for Months and Years.. If anyone know, how to do this kindly help..

FYI - https://stackblitz.com/edit/angular-date-class-filter-aactjv This is the one I found setting custom design to the dates view.. But i want similar implementation for Year and Months views.. Thanks in advance..

解决方案

Really it's a bit complex control the material angular date picker events. I don't know if there're a better aproach, but you can get it using a custom header component, see this SO

Before, we are going to create a dataService

@Injectable({
  providedIn: "root"
})
export class DataService {
  arrayOfDays = [
    new Date("2019-01-01"),
    new Date("2020-08-10"),
    new Date("2020-09-20")
  ];

  constructor() {}
  displayMonth(year: number, view: string) {
    setTimeout(() => {
      let elements = document.querySelectorAll(".mat-calendar-content");
      let x = elements[0].querySelectorAll(".mat-calendar-body-cell-content");
      if (view == "multi-year") {
        const years = this.arrayOfDays.map(x => x.getFullYear());
        x.forEach((y: any) => {
          if (years.indexOf(+y.innerHTML) >= 0) {
            {
              y.style["border-color"] = "red";
            }
          }
        });
      }
      if (view=="year"){
        const monthsIni = [
          "JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"
        ];
        const months = this.arrayOfDays
          .filter(x => x.getFullYear() == year)
          .map(x => monthsIni[x.getMonth()]);
        x.forEach((y: any) => {
          if (months.indexOf(y.innerHTML) >= 0) {
            {
              y.style["border-color"] = "red";
            }
          }
        });
      }
    });
  }
}

After inject the dataService in the ExampleHeader and in the component, in the Example header is a fwe complex but it's only write

  constructor(_intl: MatDatepickerIntl,
              @Inject(forwardRef(() => MatCalendar)) calendar: MatCalendar<any>,
              @Optional() _dateAdapter: DateAdapter<any>,
              @Optional() @Inject(MAT_DATE_FORMATS) _dateFormats: MatDateFormats,
              changeDetectorRef: ChangeDetectorRef
              ,private dataService:DataService
              ) {
    super(_intl,calendar,_dateAdapter,_dateFormats,changeDetectorRef)
  }

When handles user clicks on the period label, user clicks on the previous button and user clicks on the next button to call the service

  currentPeriodClicked(): void {
    this.calendar.currentView =
      this.calendar.currentView == "month" ? "multi-year" : "month";
    this.dataService.displayMonth(
      this.calendar.activeDate.getFullYear(),
      this.calendar.currentView
    );
  }

  customPrev(): void {
    this.previousClicked();
    this.dataService.displayMonth(
      this.calendar.activeDate.getFullYear(),
      this.calendar.currentView
    );
  }

  customNext(): void {
    this.nextClicked();
    this.dataService.displayMonth(
      this.calendar.activeDate.getFullYear(),
      this.calendar.currentView
    );
  }

Futhermore we need make it also in yearSelected from the main component

  yearSelected(event: any) {
    this.dataService.displayMonth(
      event.getFullYear(),
      this.calendar.currentView
    );
  }

You can see in the stackblitz

Update if only want to "remark" the months, the thing is more simple, because we need only control the (yearSelected) event, so we can forget about the custom header.

<mat-datepicker #picker [dateClass]="dateClass"
 (yearSelected)="yearSelected($event)"  
 [calendarHeaderComponent]="exampleHeader">
</mat-datepicker>

months = [0,3] //<--in a variable the months we want remark

yearSelected(event:any)
  {
    setTimeout(()=>{
        let elements = document.querySelectorAll(".mat-calendar-content");
        let x = elements[0].querySelectorAll(".mat-calendar-body-cell-content");
        x.forEach((y: any,month:number) => {
          if (this.months.indexOf(month) >= 0) {
            {
              y.style["border-color"] = "red";
            }
          }
        });
      }
    )
  }

see stackblitz

这篇关于如何在Angular Material日期选择器中突出显示自定义的月份和年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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