Angular 4's unique feature is the ability to incorporate multiple date pickers without the

Is there a way to implement a multiple date picker using Angular 4 and TypeScript only? I came across one solution but it seems to only support Angular 1.

Thank you in advance!

Answer №1

How can I create a multi-date-picker using ng-bootstrap date picker?

I have based my approach on the datepicker-range example from ng-bootstrap. You can view the final code at: https://stackblitz.com/edit/angular-he7fsp

Essentially, the key is to store selected dates in an array and modify the custom-day template to display the selected dates differently.

The structure of multi-date-picker.html closely resembles that of the ng-bootstrap datepicker range.

<!-- we do not use (select)="onDateSelection($event)"-->
<ngb-datepicker #dp  [displayMonths]="2" [dayTemplate]="t">
</ngb-datepicker>

<ng-template #t let-date="date" let-focused="focused">
  <!--we utilize the (click) event to pass the event and the date-->
  <span class="custom-day" (click)="onDateSelection($event,date)"
        [class.focused]="focused"
        [class.range]="isFrom(date) || isTo(date) || isInside(date) || isHovered(date)"
        [class.faded]="isHovered(date) || isInside(date)"
        <!--add a class.selected if the date belongs to our selected dates -->
        [class.selected]="isDateSelected(date)"
        (mouseenter)="hoveredDate = date"
        (mouseleave)="hoveredDate = null">
    {{ date.day }}
  </span>
</ng-template>

The code may seem intricate, but it's relatively straightforward. I've added functions like isDateSelected, addRangeDate, and addDate. Additionally, I modified the onDateSelection function to consider when the user presses the Ctrl key.

import {Component,Input,Output,EventEmitter} from '@angular/core';
import {NgbDateStruct, NgbCalendar} from '@ng-bootstrap/ng-bootstrap';

// Utility functions for date manipulation

@Component({
  selector: 'ngb-multi-date-picker',
  templateUrl: 'multi-date-picker.html',
  styles: [`
    .custom-day {
      text-align: center;
      padding: 0.185rem 0.25rem;
      display: inline-block;
      height: 2rem;
      width: 2rem;
    }
    .custom-day.range, .custom-day:hover {
      background-color: rgb(2, 117, 216);
      color: white;
    }
    .custom-day.faded {
      background-color: rgba(2, 117, 216, 0.5);
    }
    .custom-day.selected{  
      background-color: rgba(255, 255, 0, .5);

    }
  `]
})
export class MultiDatePicker {

  // Class implementation omitted for brevity
}

To use this multi-date-picker component:

<ngb-multi-date-picker [datesSelected]="datesSelected"
         (datesSelectedChange)="change($event)"></ngb-multi-date-picker>

In your AppComponent, you would have:

export class AppComponent {
  datesSelected:NgbDateStruct[]=[]; 
  change(value:NgbDateStruct[])
  {
    this.datesSelected=value;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

Encountering difficulty in presenting detailed information using a .json file

My photo gallery app functions perfectly when fetching data from jsonplaceholder.typicode.com. However, when I use my own local data, it breaks whenever I try to click on a photo to view its details. How is it possible for the photos to display correctly b ...

Nest is having trouble resolving dependencies for this service

Can multiple MongoDB models be injected into one resolver and used? I attempted to accomplish this by first adding the import of SectionSchema and SectionsService to the PostsModule: @Module({ imports: [MongooseModule.forFeature([{name: 'Post&apos ...

Angular array sanitization for handling multiple URLs

I need to sanitize multiple URLs from an array containing links to video sites e.g.: videos: SafeResourceUrl = ['www.someURL1', 'www.someURL2',... ]; To achieve this, I created a constructor like so: constructor(private sanitizer ...

Navigating after a button is clicked in Angular Material 2 tabs can be achieved by utilizing the router module in

Currently, I am utilizing Angular Material 2 tabs and have the desire for a next button in one tab that would navigate to another tab upon clicking. What specific element or function should I implement to accomplish this desired functionality? ...

Retrieving an array of objects through an Angular service

I'm fairly new to Angular and Javascript. Recently, I created an Angular service that fetches an array of users from an HTTP call returning JSON data. While the HTTP call is successful and returns the correct data, I'm having trouble passing this ...

Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice. A similar behavior has been mocked here: https://stackbl ...

My HTML files are not recognizing the IONIC Property within their own objects

As I delve deeper into understanding Angular and Ionic, a peculiar issue has arisen for which I seek a solution. I have several export classes containing HTML forms. In each corresponding .ts file, I declare a variable and import the relevant model to bin ...

What is the best way to reduce the size of TypeScript source code in an Electron application with the help of Electron Forge and Electron Packager

resolved: I was able to solve this issue using electron-builder, which utilizes webpack in the background to handle all problems efficiently. Initially, I faced this challenge while using electron-forge and electron-packager. Despite researching extensivel ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...

Deploying a Spring Boot and Angular application

Looking for guidance in creating executable files with specific commands to run projects using Eclipse STS for Spring Boot applications and VS Code for Angular. Open to exploring other solutions as well. Struggling with the process of creating an executa ...

An issue arises in VueJS when employing brackets and the replace function in Typescript

My journey with the Typescript language has just begun, and I am excited to dive deeper into it. Currently, I am working on a SPA-Wordpress project as a hobby using Vite (VueJS). However, I am facing some challenges with the syntax when transitioning from ...

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Issue with MUI 5 Button component not receiving all necessary props

Currently, I am attempting to create a customized MUI5-based button in a separate component with the following code: import {Button, buttonClasses, ButtonProps, styled} from '@mui/material'; interface MxFlatButtonProps extends Omit<ButtonProp ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

Is it feasible to verify the accuracy of the return type of a generic function in Typescript?

Is there a way to validate the result of JSON.parse for different possible types? In the APIs I'm working on, various Json fields from the database need to have specific structures. I want to check if a certain JsonValue returned from the database is ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Executing the plugin-typescript library within an Angular 2 project hosted on localhost

I am encountering an issue every time I run my angular2 project where numerous files are being loaded, including the 'ts' library from unpkg.com/plugin-typescript/lib/plugin.js. I am looking to eliminate the need for this file to load from anothe ...