How to integrate a toggle switch into an Angular datepicker component

Can the toggle switch be placed inside the calendar? I would like to have it positioned at the top of the open calendar so that users can choose to view date details using the toggle switch

<form #uploadForm="ngForm" (keydown.enter)="$event.preventDefault()">
  <div class="input-wrapper">
    <mat-form-field>
      <input
        id="date"
        name="date"
        [disabled]="datePickerDisabled || uploadForm.submitted"
        [matDatepicker]="datepicker"
        placeholder="Expiration date"
        autocomplete="off"
        matInput
        required />
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker touchUi #datepicker></mat-datepicker>
    </mat-form-field>
    <div class="tooltip">This field is required.</div>
    <mat-slide-toggle
      (change)="setMaxExpirationDate($event)">Show Date Details</mat-slide-toggle>  
  </div>
</form>

Answer №1

There are two approaches that you can take:

1. Customize the header by referring to the documentation: customizing header

Replicate the header from this SO answer:

/** Custom header component for datepicker. */
@Component({
  selector: 'example-header',
  template: `
<mat-slide-toggle
      (change)="setMaxExpirationDate($event)">Show Date Details</mat-slide-toggle> 
  <div class="mat-calendar-controls">
    <button mat-button type="button" class="mat-calendar-period-button"
            (click)="currentPeriodClicked()" [attr.aria-label]="periodButtonLabel"
            cdkAriaLive="polite">
      {{periodButtonText}}
      <div class="mat-calendar-arrow"
           [class.mat-calendar-invert]="calendar.currentView != 'month'"></div>
    </button>

    <div class="mat-calendar-spacer"></div>

    <ng-content></ng-content>

    <button mat-icon-button type="button" class="mat-calendar-previous-button"
            [disabled]="!previousEnabled()" (click)="previousClicked()"
            [attr.aria-label]="prevButtonLabel">
    </button>

    <button mat-icon-button type="button" class="mat-calendar-next-button"
            [disabled]="!nextEnabled()" (click)="nextClicked()"
            [attr.aria-label]="nextButtonLabel">
    </button>
  </div>
</div>  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleHeader extends MatCalendarHeader<any> {

  /** Handles user clicks on the period label. */
  currentPeriodClicked(): void {
    this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';
  }
}

(Make changes in the .html file to customize the controls as needed)

2. Put the mat-datepicker inside a mat-menu, as demonstrated in this another SO answer

Updated Accessing an element of the header might be challenging, but controlling the toggle is easier if you use an intermediate service. Imagine having a service like this:

@Injectable({
  providedIn: "root"
})
export class CalendarService {
  private _event = new Subject<void>();
  public onEvent = this._event as Observable<any>;
  constructor() {}

  command(value: any) {
    this._event.next(value);
  }
}

You can inject the service in the constructor of customHeader:

constructor(
    private _calendar: MatCalendar<D>,
    private _dateAdapter: DateAdapter<D>,
    @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
    cdr: ChangeDetectorRef,
    private service: CalendarService
  )

Then, if our toggle calls a function:

<mat-slide-toggle #toggle (change)="toggleChange($event)">
    Show Date Details
</mat-slide-toggle>

The function would look like this:

  toggleChange(event: any) {
    this.service.command(event);
  }

In the ngOnInit function of the component, subscribe to the service:

ngOnInit() {
    this.service.onEvent.subscribe(res => {
      console.log(res.checked);
    });
  }

You can see an example on stackblitz

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

Transfer information to a different division using Ajax

I am attempting to transfer data to another div after an Ajax refresh. Each time it refreshes, new data is fetched from the database. My goal is to retain the old data displayed in the first div, store it, and then move it to the second div when Ajax refre ...

How can I use CSS to make a child element in a grid layout stretch horizontally to full width?

I am currently working on designing a grid layout that will display a child element when clicked. Here is what I have in mind: [ link1 ] [ link2 ] [ link3 ] [ link4 ] [ link4 ] [ link4 ] When clicked, it will turn into: [ link1 ] [ link2 ] ...

How to Use JQuery to Retrieve the Nearest TD Element's Text Content

Hey there, here is some HTML code that I need help with: <tbody> <tr> <td class="text-center"><input type="text" class="form-control cardSerialNumber"></td> <td class="text-center"><button type="button" onc ...

I need the links to open up the content area on the website in HTML

Is it possible to have a fixed header that does not disappear when clicking links from the navigation bar? I tried dividing the page into tables to achieve this. Now, I want to open the links in the navigation bar in the right column (the main content col ...

What is the technique to achieve a seamless blur effect?

Is there a way to create a smooth blur similar to a gradient transitioning from transparent to dark? .img { background: url(https://4kwallpapers.com/images/walls/thumbs_2t/13551.jpg); background-size: cover; background-position: center; width: 5 ...

Show a webpage depending on specific JavaScript criteria

I have a condition in my JavaScript code that determines whether or not a user should be granted access to a specific page. However, I don't want users to be able to directly access this page even if they know the URL. This page contains both HTML and ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...

Adjust the table to line up perfectly, center the content within the table cell (td), and align the

I'm currently working on aligning a table by centering the td elements and left justifying the text inside them. My initial attempt was to use flex for center alignment, which worked to some extent but I couldn't get the left alignment right. I ...

Styling Fonts in Safari with CSS

Because FixedSys doesn't appear correctly in Chrome or Safari, I switch it to Lucida Console. While this solution works for Chrome, I encounter a problem with Safari. Unless Lucida Console stands alone, the font will not display as desired. If there a ...

Fade in elements as the cursor moves, without hovering over a specific element

I'm working on implementing a fade-in effect for content when the mouse moves (similar to Google's homepage), but I'd like to avoid this behavior if the cursor is hovering over a specific div. Here are the basics: $("html").hover(function( ...

Aligning form elements horizontally with Angular 2 Material

Thank you in advance for taking the time to assist me. Your help means a lot! I have developed a form using Angular 2 Material Design and I am facing an issue with aligning two elements. Specifically, how can I align Bill Number and Year as shown in the s ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

What is the relationship between html, body, and window when scrolling through code?

I've been working on adding a scroll-to-top button to my website. After doing some research online, I came across this code snippet: $('html, body').animate({scrollTop:0}, 'slow'); It's interesting that they are trying to scr ...

How to divide an HTML string into an array using PHP

I am in need of some assistance from you all. The issue I am facing involves dealing with a string of HTML that looks like this: <h4>Some title here</h4> <p>Lorem ipsum dolor</p> (some other HTML here) <h4>Some other title ...

JQuery unable to recognize dynamically inserted Anchor Tag through AJAX request

I am currently working on a page that is sourcing a large amount of data from a database through various PHP files. To achieve this, I am using JQuery to identify specific events and trigger AJAX requests to the necessary PHP file to display the required c ...

What is the correct method in CSS to resize an image while maintaining its proportions within a div container?

I've been struggling to properly insert images into a <div> element on my website. I've experimented with various techniques, such as setting max-width and max-height to 100%, changing the display property of the parent element to flex, and ...

Increase and decrease a counter in Javascript by clicking on two separate image tags, with increments and decrements between 1 and 10

Hello! I really appreciate your help. I am currently facing the following issue: <div id="thumb1"> <img class="img-responsive" id="prova" src="img/thumb-up-dark.png" alt=""> <div id="pinline">0</div> ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

Having trouble with utilizing pako.js in your JavaScript code? The error "Pako is not defined

I'm relatively new to the world of JavaScript. Currently, I'm tackling an algorithm that involves deflating in Java and inflating in JavaScript. While researching solutions, I came across pako.js as a recommended tool for decompression. However, ...

Allow editing for only a specific part of a text box

Creating a customized personal URL page for users on my site is important to me. I envision the value of a text box being "example.com/username," with the "example.com/" part displayed in the text box, but not editable. I've noticed that Tumblr accom ...