Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March.

https://i.sstatic.net/RhlS9.png

By using :host and ::ng-deep, I am able to override PrimeNG styles in the CSS file.

:host ::ng-deep .ui-datepicker .ui-datepicker-header .ui-datepicker-next{  
 display:none;

}

However, I want to apply these style changes within the component itself. I tried the following code, but it did not work as expected.

let datePickerNext = document.querySelectorAll('.ui-datepicker .ui-datepicker-header .ui-datepicker-prev');
datePickerNext.forEach(element => {
  element.setAttribute("style", " margin-top: 0.6em;opacity: 0.2;");
});

Does anyone have any suggestions on how to achieve this?

Answer №1

Have you found a resolution to your issue? I encountered a similar scenario in a project, and a team member suggested a solution that seems to work well on Chrome/Edge. To implement this in TypeScript, you can add one or both of these classes to the p-calendar element (ui-datepicker-prev-disable or ui-datepicker-next-disable).

:host ::ng-deep p-calendar.ui-datepicker-next-disable .ui-datepicker .ui-datepicker-header .ui-datepicker-next {
  color: #dddddd !important;
  pointer-events: none;
}

:host ::ng-deep p-calendar.ui-datepicker-prev-disable .ui-datepicker .ui-datepicker-header .ui-datepicker-prev {
  color: #dddddd !important;
  pointer-events: none;
}

I also included an event handler for onMonthChange just in case the icons are re-enabled by anyone.

In the HTML template, I added this binding. minMonth and maxMonth are variables initialized in ngOnInit and are based on the minimumDate and maximumDate.

<p-calendar #calendar
   [ngClass]="{
     'ui-datepicker-prev-disable': calendar.currentMonth === minMonth, 
      'ui-datepicker-next-disable': calendar.currentMonth === maxMonth}"

Answer №2

Yes, you can achieve this by either hiding or blurring the navigation arrows within the calendar component. To do this, you need to utilize the onMonthChange event and apply CSS changes based on the event triggered. https://i.sstatic.net/r63NQ.jpg

Below is a sample code snippet that demonstrates how to implement this:

HTML:

<p-calendar [(ngModel)]="date4" [minDate]="minDate" [maxDate]="maxDate" 
    [readonlyInput]="true" inputId="min-max" 
    (onMonthChange)="disableDatePickerPrev($event)"
    [ngClass]="{'disable-datepicker-prev': disabled}">
</p-calendar>

In the above code, the onMonthChange event is utilized to call the disableDatePickerPrev function to dynamically apply CSS changes based on the event triggered.

Typescript:

disabled:boolean = false;
disableDatePickerPrev(evt){
    // Setting the condition to disable prev month navigation
    // For example, disabling navigation for October when the current month is December
    if(evt.month <= 10) this.disabled=true;
}

CSS:

p-calendar.disable-datepicker-prev ::ng-deep .p-datepicker-prev {
    display: none;
}

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

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...

What is the best way to refresh a personalized form element using Angular?

I have developed a custom form control with validation that utilizes a standalone FormControl to manage the value and perform certain validations. Is there a method in Angular to reset the inner FormControl when the control is being reset from another For ...

The service remains operational while the button's status undergoes a change

In my data table, each row has a column containing buttons. To ensure that only the button in the clicked row is executed, I include the index of that row in the start/pause timer function. I decided to create these functions in a service so that the time ...

Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure: { "a": "b", "c": "d", "e": { "f": "g", "h": "i" } } I want to transform it into the following structure: { "name": "Root", "parent": "null", "children": [ { ...

There was an error encountered while creating a new CLI using oclif: Subsequent variable declarations must be of the same type

I've been working on developing a new CLI tool using the oclif framework and TypeScript, but I'm encountering some issues when attempting to build the project. When I generate the CLI, it results in errors. Even when I try to manually run npm bu ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

What is the method for retrieving a child element from a TemplateRef variable?

I'm currently working with a component that has a modal feature. The modal is enclosed within an <ng-template> element. <ng-template #modalm let-modal> ... <button type="button" (click)="onSubmit()" class="bt ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

Problem with Clerk's authentication() functionality

Currently facing an issue with the Clerk auth() helper (auth() documentation) while working with react and next 13 (app router). When trying to access both userId and user from auth(), const { userId, user } = auth();, it seems that userId contains a val ...

Unable to initialize a public variable due to issues with Ionic Storage retrieval

I am currently facing an issue where I am trying to assign a token stored in the Ionic storage module to a public variable. However, when I attempt to set the token and then access it from another function, I encounter an undefined error. Here is the code ...

The seamless union of Vuestic with Typescript

Seeking advice on integrating Typescript into a Vuestic project as a newcomer to Vue and Vuestic. How can I achieve this successfully? Successfully set up a new project using Vuestic CLI with the following commands: vuestic testproj npm install & ...

Updating the state on change for an array of objects: A step-by-step guide

In my current scenario, I have a state variable defined as: const [budget, setBudget] = React.useState<{ name: string; budget: number | null }[]>(); My goal is to update this state by using a TextField based on the name and value of each input ...

Understanding TypeScript's ability to infer types in generics

Exploring the world of TypeScript through a robustly typed system for REST requests. Let's dive into the code: This type is used to establish the connection between routes and their respective object types: export interface RoutesMapping { api1: ...

The requested resource could not be located at @angular/platform-browser.js

I am attempting to set up ASP.NET MVC 5 (not Core) + Angular 2.0.0 + JSPM + SystemJS + TS Loader. Upon running the application, I encounter the following error: Failed to load resource: the server responded with a status of 404 (Not Found) http://localho ...

Implementation of a recursive stream in fp-ts for paginated API with lazy evaluation

My objective involves making requests to an API for transactions and saving them to a database. The API response is paginated, so I need to read each page and save the transactions in batches. After one request/response cycle, I aim to process the data an ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

The type 'Item' cannot be assigned to type 'ReactNode'

I'm having trouble understanding the meaning of this error. I've created a Type for an array of items where each item is a string. Interestingly, when I enclose the listItem within an empty fragment, the error disappears. Is there something I&ap ...