自定义垫日历中选定的日期(Angular 材料)

问题描述 投票:0回答:1

我需要在垫子日历中标记有任何任务的日子,但我找不到为什么这段代码不起作用。

ts 来了

 dateClass(): any {
    return (date: Date): MatCalendarCellCssClasses => {
      const findDate = this.tasks.find((task) =>
        moment(task.date_required.toDate()).isSame(moment(date), 'day')
      );
      if (findDate !== undefined) {
        console.log(findDate)
        return 'date-with-task';
      } else {
        return;
      }
    };
  }

这些是组件导入

import {
  ChangeDetectorRef,
  Component,
  EventEmitter,
  HostListener,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  ViewEncapsulation,
} from '@angular/core';

变量任务是来自父组件的输入

  @Input() tasks: any[];

这是我使用 mat 日历的 html

 <div class="calendar-container" [ngStyle]="{'display': !showingCalendar ? 'none' : ''}">
        <mat-calendar class="calendar-tasks" [dateClass]="dateClass()" [(selected)]="selectedDay"
            (selectedChange)='selectedChange($event)' (monthSelected)='monthSelected($event)' [startAt]='currentMonth'>
        </mat-calendar>
        <div class="border-bottom"></div>
    </div>

另外,我在 scss 中创建了这个类,这样我就可以看看代码是否有效

  .date-with-task{
    border-color: red;
  }

我阅读了我能找到的所有论坛,还观看了一些有关 mat calendas 的 yt 视频,但我找不到答案。如果有人可以帮助我,我将非常感激:)

我需要找到任务标记为红色的日子,但什么也没发生

angular sass angular-material calendar
1个回答
0
投票

您的代码存在一些问题:

  1. 您将

    dateClass() {}
    声明为常规(作用域)函数

    这意味着在其中,

    this
    是函数的作用域,而不是类实例。
    要通过
    this
    访问类实例,您必须使用 箭头函数 1:

export class MyComponent {
  @Input() tasks: any[];

  dateClass = (date: Date): MatCalendarCellCssClasses => {
    console.log(this.tasks) // inside your function was `undefined`
    if (someCondition) {
      return 'some-class'
    }
  }
}
  1. 您可能不想设计
    <button />

    上述类返回的类将应用于
    button.mat-calendar-body-cell
    。如果您设置这些元素的样式,两个相邻的日期将相互接触。我建议你设计内部
    .mat-calendar-body-cell-content
    :
.test-class .mat-calendar-body-cell-content {
  border-color: red;
}
  • 此外,如果您决定对按钮而不是单元格内容进行样式设置,请注意它们当前使用
    border: none
    进行样式设置,这意味着您需要设置多个
    border-color
    border: 1px solid red
    可以工作)。
  1. 最后但并非最不重要的一点是,因为您不是在设计组件的 DOM 元素,而是为
    <mat-calendar>
    的内部 DOM 元素设计样式,所以您需要取消 (S)CSS 的作用域,使用:
@Component({
  encapsulation: ViewEncapsulation.None
})

工作示例 2, 3.


1 - 应修改函数以根据您的业务逻辑返回字符串。
2 - 示例中

dateClass
的更详细版本为:

dateClass = (date: Date): MatCalendarCellCssClasses => {
  if (
    this.tasks
      .map((t) => t.date_required)
      .find((d) => moment(d).isSame(date, 'day'))
  ) {
    return 'test-class'
  }
  return ''
}

3 - 或者,您可以将

dateClass
输入为:

dateClass: MatCalendarCellClassFunction<Date> = (date) =>
    this.tasks
      .map((t) => t.date_required)
      .find((d) => moment(d).isSame(date, 'day'))
      ? 'test-class'
      : '';
© www.soinside.com 2019 - 2024. All rights reserved.