Highlighting certain dates in mat-calendar

前端 未结 3 1644
眼角桃花
眼角桃花 2021-02-05 21:33

I am using mat-calendar. I am trying to highlight certain dates but I couldn\'t do it. There is no proper documentation for this.

HTML

相关标签:
3条回答
  • 2021-02-05 21:57

    You can use the the input binding dateClass as describe in the Angular Material documentation here. Note: This requires an Angular Material version of at least 7.1.0

    Change your template to this:

    <mat-calendar [dateClass]="dateClass()" [selected]="selectedDate" (selectedChange)="onSelect($event)"></mat-calendar>
    

    And in your component add the dateClass function which will generate a function that will return a type of MatCalendarCellCssClasses, which can be as simple as a string representing the CSS class to apply (or an array of class names):

    dateClass() {
      return (date: Date): MatCalendarCellCssClasses => {
        if (date.getDate() === 1) {
          return 'special-date';
        } else {
          return;
        }
      };
    }
    

    And finally in your styles.css add the classes you want applied:

    .special-date {
      background-color: red;
    }
    

    Here is a stackblitz that colors the first of each month in red.

    0 讨论(0)
  • 2021-02-05 22:05

    if datas are loaded through service then you have to use *ngIf="datas" on the mat-calendar, so that dateClass will called after the data comes in. ie:

    html:

    <div *ngIf="datas">
      <mat-calendar [dateClass]="dateClass()" ></mat-calendar>
     </div>
    

    ts:

    dateClass() {
      return (date: Date): MatCalendarCellCssClasses => {
        const highlightDate = this.datas.map(strDate => new Date(strDate))
          .some(d => d.getDate() === date.getDate() && d.getMonth() === date.getMonth() && d.getFullYear() === date.getFullYear());
        return highlightDate ? 'special-date' : '';
      };
    }
    
    
    ngOnInit() {
      this.studentreportsService.getHeatMap(this.studentid)
      .subscribe(data => {
        this.datas = data; // ["2019-01-22", "2019-01-24"]
      });
    }
    
    0 讨论(0)
  • 2021-02-05 22:15

    Complementing Fabian's answer, if you have problem seeing the highlighted color and you are using lazy loading components, remember to add the ::ng-deep in front of the class. Like this:

    ::ng-deep.special-date {
       background-color: red;
    }
    

    Cheers!

    0 讨论(0)
提交回复
热议问题