要在mat-datepicker中高亮特定日期,你可以使用mat-calendar的addOverlay方法来添加一个自定义的覆盖层。下面是一个使用Angular 5和Angular Material的示例代码:
npm install --save @angular/material @angular/cdk
在app.module.ts中导入相关模块:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule, MatDatepickerModule, MatInputModule } from '@angular/material';
import { OverlayModule } from '@angular/cdk/overlay';
@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule,
MatDatepickerModule,
MatInputModule,
OverlayModule
],
declarations: [],
bootstrap: [],
providers: []
})
export class AppModule { }
import { Component, Input, OnInit } from '@angular/core';
import { MatCalendarCellCssClasses } from '@angular/material/datepicker';
@Component({
selector: 'app-highlight-overlay',
template: `
`,
styles: [`
.highlight-overlay {
position: absolute;
background-color: rgba(255, 0, 0, 0.5);
}
`]
})
export class HighlightOverlayComponent implements OnInit {
@Input() cellClass: MatCalendarCellCssClasses;
@Input() top: number;
@Input() left: number;
@Input() width: number;
@Input() height: number;
ngOnInit() { }
}
import { Component } from '@angular/core';
import { MatCalendarCellCssClasses } from '@angular/material/datepicker';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
import { HighlightOverlayComponent } from './highlight-overlay.component';
@Component({
selector: 'app-date-picker',
template: `
`
})
export class DatePickerComponent {
private overlayRef: OverlayRef;
constructor(private overlay: Overlay) { }
openOverlay() {
this.overlayRef = this.overlay.create();
const componentPortal = new ComponentPortal(HighlightOverlayComponent);
const componentRef = this.overlayRef.attach(componentPortal);
componentRef.instance.cellClass = (date: Date): MatCalendarCellCssClasses => {
return (date.getDate() === 15 && date.getMonth() === 0) ? 'highlight' : '';
};
componentRef.instance.top = 50; // 设置覆盖层位置和尺寸
componentRef.instance.left = 50;
componentRef.instance.width = 100;
componentRef.instance.height = 100;
}
}
.highlight {
background-color: rgba(255, 0, 0, 0.5) !important;
}
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
现在,当日期选择器中的日期为1月15日时,你会看到一个红色的覆盖层。
请注意,这只是一个简单的示例,你可以根据你的需求进行修改和扩展。