Hide Weekends In DevExtreme Scheduler: A Tutorial

by Rajiv Sharma 50 views

Have you ever found yourself needing to customize your DevExtreme Scheduler to hide those pesky weekends? It's a common requirement for many applications, especially those focused on business days or specific weekday activities. If you're scratching your head wondering how to achieve this in your Angular project with DevExtreme, you've come to the right place! In this article, we'll dive deep into the process, providing a step-by-step guide and practical examples to help you master this customization.

Understanding the Challenge

Before we jump into the code, let's understand the core challenge. The DevExtreme Scheduler is a powerful component that offers a wide range of features, including day, week, and month views. By default, it displays all days of the week, including weekends. However, in many scenarios, such as scheduling business meetings, appointments, or tasks, weekends are irrelevant and can clutter the view. The goal is to hide these weekends, presenting a cleaner and more focused view that only shows weekdays.

Why Hide Weekends?

  • Improved User Experience: Hiding weekends reduces visual clutter and makes it easier for users to focus on relevant time slots.
  • Business-Specific Applications: For applications that primarily deal with business days, hiding weekends aligns the scheduler with the actual operational schedule.
  • Enhanced Clarity: By removing weekends, the scheduler provides a clearer picture of the working week, making it easier to plan and manage activities.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  • Angular CLI: Ensure you have the Angular CLI installed globally (npm install -g @angular/cli).
  • DevExtreme: You should have DevExtreme installed and configured in your Angular project. If not, follow the official DevExtreme documentation for installation instructions.
  • Basic DevExtreme Scheduler Knowledge: Familiarity with the DevExtreme Scheduler component and its basic configuration is essential.

Step-by-Step Guide to Hiding Weekends

Now, let's get our hands dirty with the code. We'll explore a few methods to hide weekends in your DevExtreme Scheduler. We'll start with the most straightforward approach and then delve into more advanced techniques.

Method 1: Using the excludedDays Option

The simplest way to hide weekends is by using the excludedDays option provided by the DevExtreme Scheduler. This option allows you to specify an array of days that should be excluded from the view. In our case, we want to exclude Saturdays and Sundays, which correspond to days 6 and 0 in the JavaScript Date object (where 0 is Sunday, 1 is Monday, and so on).

Implementation

  1. Update the Scheduler Configuration:

    Open your Angular component's TypeScript file (e.g., my-component.component.ts) and add the excludedDays option to your scheduler configuration.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.css']
    })
    export class MyComponent {
      planQRuta: any[] = [...]; // Your data source
      schedulerSettings: any = {
        dataSource: this.planQRuta,
        views: ['day', 'week', 'workWeek', 'month'],
        currentView: 'workWeek',
        excludedDays: [0, 6],
        height: 600
      };
    }
    

    In this code snippet, we've added the excludedDays: [0, 6] line to the schedulerSettings object. This tells the scheduler to exclude Sundays (0) and Saturdays (6) from the view.

  2. Bind the Configuration to the Scheduler:

    In your component's HTML template (e.g., my-component.component.html), bind the schedulerSettings object to the dx-scheduler component.

    <dx-scheduler [dataSource]="schedulerSettings.dataSource" [views]="schedulerSettings.views" [currentView]="schedulerSettings.currentView" [excludedDays]="schedulerSettings.excludedDays" [height]="schedulerSettings.height">
    </dx-scheduler>
    

    Alternatively, you can bind the entire schedulerSettings object:

    <dx-scheduler [options]="schedulerSettings">
    </dx-scheduler>
    
  3. Run Your Application:

    Now, run your Angular application using ng serve. You should see the DevExtreme Scheduler with weekends hidden in the workWeek view.

Explanation

  • The excludedDays option is an array that accepts numbers representing the days of the week (0-6). By specifying [0, 6], we instruct the scheduler to exclude Sundays and Saturdays.
  • This method is the simplest and most direct way to hide weekends, making it suitable for most common scenarios.

Method 2: Customizing Views

Another approach is to customize the views available in the scheduler. Instead of hiding weekends in existing views, we can create a custom view that only displays weekdays. This method provides more control over the scheduler's behavior and appearance.

Implementation

  1. Define a Custom View:

    In your component's TypeScript file, define a custom view configuration that excludes weekends.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.component.css']
    })
    export class MyComponent {
      planQRuta: any[] = [...]; // Your data source
      schedulerSettings: any = {
        dataSource: this.planQRuta,
        views: ['day', 'week', 'workWeek', 'month', {
          type: 'week',
          name: 'Custom Week',
          intervalCount: 1,
          excludedDays: [0, 6]
        }],
        currentView: 'workWeek',
        height: 600
      };
    }
    

    Here, we've added a custom view to the views array. The custom view has the following properties:

    • type: Specifies the view type ('week' in this case).
    • name: The name displayed in the view switcher.
    • intervalCount: The number of weeks displayed in the view.
    • excludedDays: The days to exclude from the view (Sundays and Saturdays).
  2. Bind the Configuration to the Scheduler:

    In your component's HTML template, bind the schedulerSettings object to the dx-scheduler component.

    <dx-scheduler [options]="schedulerSettings">
    </dx-scheduler>
    
  3. Run Your Application:

    Run your Angular application. You should see the new "Custom Week" view in the view switcher, which excludes weekends.

Explanation

  • By defining a custom view, we have more control over the scheduler's behavior. This method is useful when you need to provide different views with specific configurations.
  • The name property allows you to provide a user-friendly name for the custom view.
  • You can define multiple custom views with different configurations to cater to various user requirements.

Method 3: Using CSS to Hide Weekends (Less Recommended)

While not the most recommended approach, you can also use CSS to hide weekends. This method involves targeting specific cells in the scheduler's table structure and applying CSS rules to hide them. However, this approach is less robust and may break if the DevExtreme Scheduler's internal structure changes in future updates.

Implementation

  1. Inspect the Scheduler's Structure:

    Use your browser's developer tools to inspect the DevExtreme Scheduler's HTML structure. Identify the CSS classes or elements that represent weekend cells.

  2. Add CSS Rules:

    Add CSS rules to your component's CSS file (e.g., my-component.component.css) to hide the weekend cells.

    .dx-scheduler-date-table-cell.dx-scheduler-date-table-weekend {
      display: none;
    }
    

    This CSS rule targets cells with both the dx-scheduler-date-table-cell and dx-scheduler-date-table-weekend classes and sets their display property to none, effectively hiding them.

  3. Run Your Application:

    Run your Angular application. The weekends should be hidden in the scheduler.

Explanation

  • This method relies on the DevExtreme Scheduler's internal structure, which may change in future versions, making it less reliable.
  • It's generally recommended to use the excludedDays option or custom views for hiding weekends, as they are more robust and maintainable.
  • Use this method with caution and be prepared to update your CSS rules if the scheduler's structure changes.

Advanced Customization

Now that we've covered the basics of hiding weekends, let's explore some advanced customization options.

Dynamic Weekend Exclusion

In some scenarios, you may need to dynamically exclude weekends based on certain conditions. For example, you might want to exclude specific dates or date ranges in addition to the standard weekends. You can achieve this by programmatically updating the excludedDays array or by using a custom filter function.

Example: Excluding Specific Dates

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  planQRuta: any[] = [...]; // Your data source
  schedulerSettings: any = {
    dataSource: this.planQRuta,
    views: ['day', 'week', 'workWeek', 'month'],
    currentView: 'workWeek',
    excludedDays: [0, 6],
    height: 600,
    // Add this function
    dateCellTemplate: (itemData: any, itemIndex: number, cellElement: any) => {
      const date = itemData.startDate;
      const excludedDates = [new Date('2024-07-04'), new Date('2024-07-05')]; // Example dates
      if (excludedDates.some(d => d.getTime() === date.getTime())) {
        cellElement.classList.add('dx-scheduler-date-table-cell-excluded');
      }
    }
  };

    ngOnInit() {
      //add an array with specific dates to exclude
      const specificDatesToExclude = [new Date('2024-07-06'), new Date('2024-07-07')];
      this.schedulerSettings.excludedDays = [...this.schedulerSettings.excludedDays, ...specificDatesToExclude.map(date => date.getDay())];
    }
}

In this example, we've added a function to the dateCellTemplate option to check if the cell's date is in the excludedDates array. If it is, we add a CSS class to the cell to visually indicate that it's excluded. You can then define CSS rules to style the excluded cells as needed.

Custom Date Formatting

You might also want to customize the date formatting in the scheduler to reflect the exclusion of weekends. For example, you could display a message indicating that weekends are excluded or use a different date format that only shows weekdays.

Best Practices

To ensure a smooth and maintainable implementation, consider the following best practices:

  • Use the excludedDays Option: This is the simplest and most recommended way to hide weekends.
  • Create Custom Views: If you need more control over the scheduler's behavior, create custom views with specific configurations.
  • Avoid CSS Hacks: Using CSS to hide weekends is less robust and may break in future updates.
  • Test Thoroughly: Always test your implementation thoroughly to ensure that weekends are hidden correctly and that the scheduler behaves as expected.
  • Document Your Code: Add comments to your code to explain the logic behind your customizations.

Conclusion

Hiding weekends in the DevExtreme Scheduler is a common requirement for many applications. By using the excludedDays option, creating custom views, or implementing dynamic exclusion logic, you can tailor the scheduler to meet your specific needs. Remember to follow best practices and test your implementation thoroughly to ensure a smooth and maintainable solution. With the knowledge and techniques shared in this article, you're well-equipped to create a DevExtreme Scheduler that perfectly fits your application's requirements.

Guys, I hope this comprehensive guide has been helpful in mastering weekend hiding in DevExtreme Scheduler! Happy coding!