in my DatePicker <mat-calendar>
from Angular Material I want to highlight multiple dates that I read from an HTTP request.
I am using Spring Boot as the backend for my application. There I have the entity "Lunch" which has the attribute "LocalDate date"
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Builder
@FieldDefaults(level = AccessLevel.PRIVATE)
@Table(name = "lunch")
public class Lunch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@NotNull(message = "date can't be null")
@Column(columnDefinition = "DATE")
LocalDate date;
.
.
}
I first tried to store the data of this attribute with a GET request in a property in Angular and then read this property in MatCalendarCellCssClasses.
@Component({
selector: 'app-calendar',
templateUrl: './calendar.component.html',
styleUrls: ['./calendar.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class CalendarComponent implements OnInit {
@Output()
public changedDateValue = new EventEmitter<Date>();
public selectedDate: Date = new Date();
public dates: Date[] = [];
constructor(private readonly lunchApiService: LunchApiService) { }
public dateClass() {
return (date: Date): MatCalendarCellCssClasses => {
const highlightDate = this.dates
.some(d => d.getDate() === date.getDate() && d.getMonth() === date.getMonth() && d.getFullYear() === date.getFullYear());
return highlightDate ? 'special-date' : 'normal-date';
};
}
public onChangedDate(): void {
this.changedDateValue.emit(this.selectedDate);
}
public ngOnInit(): void {
this.subs.add = this.lunchApiService.findAll().subscribe(
data => {
// let x: string[][] = data.map(a => a.date.toString().split(/[x^-]/));
// let n: number[] = x.map(a => +a[2].replace(/^0+/, ''));
data.forEach(a => this.dates.push(a.date)); // return [ '2022-07-14', '2022-07-15', ... ]
});
}
}
<mat-card class="calendar">
<mat-calendar [(selected)]="selectedDate"
(selectedChange)="onChangedDate()"
[dateClass]="dateClass()"></mat-calendar>
</mat-card>
It did not work. What am I doing wrong? How else can I implement my idea?