how to customize angular mat date picker input field

27 Views Asked by At

I'm trying to use a simple date range picker in my Angular app. how to set the width and height of angular material date picker input field.

my html -

<div class="no-bottom">
  <mat-form-field appearance="outline">
    <mat-label>Datumsbereich</mat-label>
    <mat-date-range-input [formGroup]="range" [rangePicker]="picker">
      <input matStartDate formControlName="start" placeholder="Startdatum">
      <input matEndDate formControlName="end" placeholder="Endtermin">
    </mat-date-range-input>
    <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
    <mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-date-range-picker #picker></mat-date-range-picker>
  </mat-form-field>
</div>

my css -

.no-bottom {
   margin-bottom: -1.25em !important;
}

my component -

import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { NativeDateAdapter } from '@angular/material/core';

@Component({
  selector: 'date-range-picker',
  templateUrl: './date-range-picker.component.html',
  styleUrls: ['./date-range-picker.component.scss'],
  providers: [NativeDateAdapter],
})
export class DateRangePickerComponent {
  @Output() rangeChange = new EventEmitter<FormGroup<any>>();
  
  range = new FormGroup({
    start: new FormControl<Date | null>(null),
    end: new FormControl<Date | null>(null),
  });

  constructor() {
    this.range.valueChanges.subscribe(value => {
      this.rangeChange.emit(this.range); 
    });
  }
}

need the input field to be same height as the button in the left side, which is 35pxenter image description here

1

There are 1 best solutions below

3
Alpine A110R On BEST ANSWER

You can't set the width and height of mat-form-field host element. A component styles is encapsulated within the component's host element so that they don't affect the rest of your component.

Angular provides ViewEncapsulation.None :

The styles of components are added to the of the document, making them available throughout the application, so are completely global and affect any matching elements within the document.

You need to make these changes to set the width or height:

@Component({
  selector: 'date-range-picker',
  templateUrl: './date-range-picker.component.html',
  styleUrls: ['./date-range-picker.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: [NativeDateAdapter],
}) ....

// date-range-picker.component.scss

With styles scoped to the component :

date-range-picker {
 // apply styles to a host element 
 .mat-mdc-form-field-flex {
   width: 100px;
   height: 35px;
 }
}