I have a problem. I want to use a date-picker
for an Angular form but I need to select only the year and the month, no need to select the day. What is the simple way to do that? Also I want to know how to take year and month separately to a .ts
file.
CodePudding user response:
You can use Angular Material DatePicker with this workaround:
HTML:
<mat-form-field>
<input #dpInput matInput [matDatepicker]="dp" placeholder="datepicker" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp (monthSelected)="monthSelected($event, dp, dpInput)" startView="multi-year"></mat-datepicker>
</mat-form-field>
ts:
@Component({
selector: 'datepicker-example',
templateUrl: 'datepicker-example.component.html',
styleUrls: ['datepicker-example.component.css'],
})
export class DatepickerFormatsExampleComponent {
date = new FormControl(moment());
monthSelected(event, dp, input) {
dp.close();
input.value = event.toISOString().split('-').join('/').substr(0, 7);
}
}
The monthSelected
function will get the datePicker and input references and will extract the selected data and set the value of input.
For the other part of your question, you can use monthSelected
and yearSelected
event, but they pass the entire date. What you can do is to extract these amount of the date object by the following:
const array = event.toISOString().split('-');
const year = array[0];
const month = array[1];