Need to change default date when not selecting a date in matdatepicker - html

When I am not selecting a date in matdatepicker (angular2), it's taking the default value as "01/01/1970", whereas I need to pass 'null' to the method. Can I change the default value somehow?
Code I am using is as below:
HTML:
<div class="div1">
<form (ngSubmit)="getEventsByDateRange(f)" #f="ngForm" >
<label style="float:left;padding:7px;"> From : </label>
<mat-form-field style="float:left;padding:7px;">
<input type="date" matInput [matDatepicker]="picker1" placeholder="Choose a date" name="fromDate"
[(ngModel)]="eventobj.fromDate" #eventDate="ngModel" required>
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
<label style="float:left;padding:7px;"> To : </label>
<mat-form-field style="float:left;padding:7px;">
<input type="date" matInput [matDatepicker]="picker2" placeholder="Choose a date" name="toDate"
[(ngModel)]="eventobj.toDate" #eventDate="ngModel" required>
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
<button mat-raised-button class="btn btn-info btn-sm"> Submit </button>
</form>
</div>
TS:
eventobj = {
fromDate: "Date",
toDate: "Date",
}
getJobsByDateRange() {
let fromDate1=new Date(this.eventobj.fromDate)
let toDate1=new Date(this.eventobj.toDate)
alert("from :: "+fromDate1+" to :: "+toDate1)
}
If I am clicking on submit button directly then the alert message shows :
from :: Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time) to :: Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

eventobj = {
fromDate: "Date",
toDate: "Date",
}
Here, you declare strings. But you use dates ...
Anyway, this means that when you do
let fromDate1=new Date(this.eventobj.fromDate)
let toDate1=new Date(this.eventobj.toDate)
You actually convert a string (being Date) to an actual date. You're lucky uou have a date object !
Replace all of that with this :
defaultDate = Date.now();
eventobj = {
fromDate: new Date(this.defaultDate - 1000 * 60 * 60 * 24 * 7), // One week
toDate: new Date(this.defaultDate),
}
getJobsByDateRange() {
let fromDate1 = this.eventobj.fromDate;
let toDate1 = this.eventobj.toDate;
alert("from :: "+fromDate1+" to :: "+toDate1)
}

Related

Reset a mat-date-range-input

I am trying to reset the content of a mat-date-range-input, but cannot find how
The input itself looks like this :
<mat-form-field appearance="fill" class="calendar-form-field">
<mat-label>Date</mat-label>
<mat-date-range-input [rangePicker]="datePicker" disabled >
<input matStartDate #dateStart placeholder="Start">
<input matEndDate #dateEnd placeholder="End" (dateChange)="dateChange(dateStart.value, dateEnd.value)">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
<mat-date-range-picker #datePicker [calendarHeaderComponent]="calendarHeader" disabled="false">
<mat-datepicker-actions>
<button mat-button matDatepickerCancel>Cancel</button>
<button mat-raised-button matDatepickerApply>Ok</button>
</mat-datepicker-actions>
</mat-date-range-picker>
</mat-form-field>
I would like to be able to reset it with a button, which would trigger a function (which also reset multiple other fields, and some data, omitted in this question. As such, the reset has to be on the Typescript side).
I already tried multiples solution (ViewChild, bindings, etc.) found here and there (Stackoverflow as well as dozen of blogs found via google), but none of those solutions worked. I'm still new to Angular, so it may be just me who badly implemented those solutions, so if you think one of the solutions I tried is the good one, do not hesitate to post it.
You can use the formgroup to make thing work and if you want to reset, just set the value for start, end to null or whatever you want to make it default;
HTML PART:
<mat-form-field appearance="fill">
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [formGroup]="range" [rangePicker]="picker">
<input matStartDate formControlName="start" placeholder="Start date">
<input matEndDate formControlName="end" placeholder="End date">
</mat-date-range-input>
<mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
<mat-error *ngIf="range.controls.start.hasError('matStartDateInvalid')">Invalid start date</mat-error>
<mat-error *ngIf="range.controls.end.hasError('matEndDateInvalid')">Invalid end date</mat-error>
</mat-form-field>
<input type="button" value="reset" (click)="resetRange()" >
<p>Selected range: {{range.value | json}}</p>
TS Part:
range = new FormGroup({
start: new FormControl<Date | null>(null),
end: new FormControl<Date | null>(null),
});
resetRange() {
this.range.patchValue({
start: null,
end: null,
});
}
Here is Example
<input matStartDate #startDate>
<input matEndDate #endDate>
...
<button mat-button (click)="startDate.value = ''; endDate.value = ''">reset</button>

Having both date and string in value for the Input field in html

I have a placeholder that have a string and a value with date type format.
Here is the code:
<mat-form-field>
<input matInput placeholder="Start Date" [value]="leave.FullStartDate | date:'a'" disabled>
</mat-form-field>
I want to have the [value] that can contain a date and a string. I try adding a string called "start" but it doesn't work:
<mat-form-field>
<input matInput placeholder="Start Date" [value]="leave.FullStartDate | date:'a' start" disabled>
</mat-form-field>
The logic is that I want the outcome to be as "AM start" instead of "AM", in which "AM" is the date and "start" as a string but I couldn't. Right now is just AM. Please help how can I have date formate with a string in the [value]
Here how it looks right now:

set datepicker value automatically based on previous datepicker in angular(setvalue)

I have two datepickers picker1 and picker2. What I am trying to to is that when I select a date in picker1 the picker2 should automatically get selected and the date in the picker2 should be 60 days from date in picker1
For example if its march 1 2021 in picker1 It should be april 29 2021 in picker2
I have searched for various solutions in stackoverflow but couldn't get the exact solution.
Pleease help if u guys know
Datepicker1:
<td>
<mat-form-field >
<input matInput readonly [matDatepicker]="picker1" formControlName="startdate"
(dateChange)="setDate($event.value)"placeholder="Start Date">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</td>
Datepicker2
<td>
<mat-form-field>
<input matInput readonly [matDatepicker]="picker2" formControlName="enddate"
placeholder="End Date">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</td>
My ts
setDate(a) {
this.datecheck = this.eventaddform.value.startdate+60
this.eventaddform.patchValue({
expirydate: this.datecheck
})
}
I have created a sample stackblitz justincase if u guys need something to work with
Stackblitz: https://stackblitz.com/edit/angular-date-picker-sample-fr-h19bes?file=app%2Fapp.component.html
Use dateChange event from picker1 to set picker2 by binding value
I've created a basic stackblitz example removing Forms
DEMO
PS: adding 60 to March 01 2021 gave me April 30 2021. So you can try adding 59

Angular binding for datetime input field min and max value

I don't know if there is a way to bind variable values from .ts file to input value, min and max properties.
I've tried many ways, but none seems to be working.
I have two-way biding to get the value from input field [(ngModel)]="transferPoint.arrivalTime, but I need to set min and max properties to certain values.
This is not working: min='{{flight.departureTime}}'
This is my html file
<h1 mat-dialog-title>ADD NEW TRANSFER POINT</h1>
<div mat-dialog-content>
<mat-form-field>
<input type="datetime-local" id="arrival-time" name="arrival-time" value="{{flight.departureTime}}" min="{{flight.departureTime}}"
max="{{flight.arrivalTime}}" matInput [(ngModel)]="transferPoint.arrivalTime" placeholder="Arrival time">
</mat-form-field>
<br>
<mat-form-field>
<input type="datetime-local" id="departure-time" name="departure-time" value="2018-06-12T19:30" min="2018-06-07T00:00"
max="2018-06-14T00:00" matInput [(ngModel)]="transferPoint.departureTime" placeholder="Departure time">
</mat-form-field>
<br>
<mat-form-field>
<input matInput [(ngModel)]="transferPoint.countryAndCity" placeholder="Country and City">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button class="submitbtn" mat-raised-button (click)='addTransferPoint()'>ADD</button>
<button class="cancelbtn" mat-raised-button mat-dialog-close>CANCEL</button>
</div>
and here is my .ts file
export class AddTransferPointComponent implements OnInit {
errorMessage: string;
flightId: any;
flight: FlightDTO;
transferPoint: TransferPointDTO = new TransferPointDTO();
constructor(#Inject(MAT_DIALOG_DATA) public data: any,
public dialogRef: MatDialogRef<any>,
private transferPointService: TransferService,
private flightService: FlightService) { }
ngOnInit() {
this.flightId = this.data.flight;
}
getFlight() {
this.flightService.getFlight(this.flightId).subscribe(
data => {
this.flight = data;
}
)
}
addTransferPoint() {
this.transferPoint.flightId = this.flightId;
this.transferPointService.createTransferPoint(this.transferPoint).subscribe(
data => {
this.dialogRef.close();
location.reload();
},
error => {
console.log(error);
this.errorMessage = error.error.message;
}
);
}
}
You can use property binding (see also https://angular.io/guide/template-syntax):
<input type="datetime-local" id="arrival-time" name="arrival-time" [value]="flight.departureTime" [min]="flight.departureTime" [max]="flight.arrivalTime" matInput [(ngModel)]="transferPoint.arrivalTime" placeholder="Arrival time">
I ran into a similar problem trying to do a matInput type="datetime-local". When I debugged it it looks like what goes into the [min] directive needs to be formatted into a string it can understand.... Essentially pass it a string in this format:
YYYY-MM-DDTHH:MM
Perhaps not the most optimal, but in my case when I switched my data like this it works
var month = this.formatDate(min.getMonth() + 1);
var day = this.formatDate(min.getDate());
this.minDate = min.getFullYear() + "-" + month + "-" + day + "T00:00";
where formatDate is:
private formatDate(nmbr: number): string {
var date = nmbr + "";
date = (date.length < 2) ? "0" + date : date;
return date;
}
Then I can use it in the directive:
<input id="eventTime" matInput type="datetime-local" [min]="minDate" name="eventTime">

How disable all the dates before a particular date in angular?

I am building a component (html, css, spec.ts, ts) in angular in which I always want endDate > startDate. I have followed this link https://material.angular.io/components/datepicker/overview in order make multiple datepickers.
Below is my HTML for startDate and endDate:
startDate:
<div class="start-date" fxFlex="50%" fxFlexOrder="1">
<mat-form-field>
<input matInput [matDatepicker]="picker1" placeholder="{{'PORTAL.STARTDATE' | translate}}" type="text" formControlName="startDate" [(ngModel)]="unavailability.startDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
</div>
endDate:
<div class="end-date" fxFlex="50%" fxFlexOrder="2">
<mat-form-field>
<input matInput [matDatepicker]="picker2" placeholder="{{'PORTAL.ENDDATE' | translate}}" type="text" formControlName="endDate" [(ngModel)]="unavailability.endDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
Now below is my angular code (ts) where I am calling validateForm method on the page load.
ngOnInit() {
....
this.validateForm();
}
validateForm() {
this.unavailabilityForm = this.formBuilder.group({
'startDate': ['', Validators.required],
'endDate': ['', Validators.required],
'unavailabilityReason': ['']
});
}
ProblemStatement:
Now what I need to do is - if I have selected any date in startDate (for example 23rd Nov), then in the endDate datepicker all the dates before and including 23rd Nov should be disabled so that I can only select dates after 23rd Nov only. Is this possible to do in Angular?
Can we achieve that by placing minDate and maxDate somewhere in HTML or TS ?
Binding with [min] works perfect for any date
.ts file
//today's date
todayDate:Date = new Date();
//any date
someDate: Date = new Date(anydate);
.html file
<mat-form-field>
<input matInput [matDatepicker]="picker" [min]="todayDate" placeholder="Appointment date" formControlName="appointment_date">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
Since you are using a reactive form, utilize the form controls. It's not recommended to have two bindings (ngModel and formControl). So drop the ngModel like I suggested in a previous question of yours: https://stackoverflow.com/a/47426879/6294072
So populate your form controls with the values of from your object unavailability.
constructor(private formBuilder: FormBuilder) {
this.unavailabilityForm = this.formBuilder.group({
startDate: [this.unavailability.startDate],
endDate: [this.unavailability.endDate]
});
}
if you are receiving the values at a later point you can use patchValues:
this.unavailabilityForm.setValue({
startDate: this.unavailability.startDate;
endDate: this.unavailability.endDate;
})
else you can set the values when you build the form.
Then the only thing you need to add to your second datepicker is [min] like the other answer mentioned. There utilize the form control value:
<input matInput
[min]="unavailabilityForm.controls.startDate.value"
formControlName="endDate" ...>
DEMO
Unless I'm missing something, you can use the [min]="" date property:
<div class="item item-2" fxFlex="50%" fxFlexOrder="2">
<mat-form-field>
<input matInput [min]="startDate" [matDatepicker]="picker2" placeholder="{{'PORTAL.ENDDATE' | translate}}" type="text" formControlName="endDate" [(ngModel)]="unavailability.endDate" [readonly]="!componentPermission.writePermission">
<mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
<mat-datepicker #picker2></mat-datepicker>
</mat-form-field>
</div>
Whatever startDate is will limit the Calendar dates available for endDate. If you need it set before startDate is chosen, use another variable and set it in consturctor() or ngOnInit() of your component.
See: https://material.angular.io/components/datepicker/overview#date-validation
Using the valueChanges of Angular reactive forms and Min feature here is a complete working solution with validation and reactive forms
you can also see the image that the publishedTo only accepts values greater than or equal to any values you set on the PublisedFrom
components.ts
export class AnnouncementformComponent implements OnInit {
constructor(private _formBuilder: FormBuilder){}
Announcementform: FormGroup;
minDate:Date;
this.Announcementform = this._formBuilder.group({
PublishedFrom: ['', Validators.required],
PublishedTo: ['', Validators.required],
});
this.Announcementform.valueChanges.subscribe(res=>{
this.minDate = new Date(res.PublishedFrom);
});
component.html
<mat-form-field appearance="outline">
<input matInput [matDatepicker]="PublishedFrom" placeholder="Publish FROM *"
formControlName="PublishedFrom">
<mat-label>Publish FROM *</mat-label>
<mat-datepicker-toggle matSuffix [for]="PublishedFrom"></mat-datepicker-toggle>
<mat-datepicker #PublishedFrom></mat-datepicker>
</mat-form-field>
<mat-form-field appearance="outline">
<input matInput [matDatepicker]="PublishedTo" placeholder="Publish To *"
formControlName="PublishedTo" [min]="minDate">
<mat-label>Publish TO *</mat-label>
<mat-datepicker-toggle matSuffix [for]="PublishedTo"></mat-datepicker-toggle>
<mat-datepicker #PublishedTo></mat-datepicker>
</mat-form-field>
I am also writing additional code below if someone needs to start his date from a specific date or greater or equal to current date can use simple line of code below
1- create a variable in your component class name it for example startDate
startDate:Date;
ngOnInit() {
//---This will set the datepicker to accept values from current date or above---//
//--- you can also customize the value to set any date you want----//
this.startDate= new Date();
}
then in your component.html file
<mat-form-field appearance="outline">
<input matInput [matDatepicker]="publishdate" placeholder="Publish Date *"
formControlName="publishdate" [min]="startDate">
<mat-datepicker-toggle matSuffix [for]="publishdate"></mat-datepicker-toggle>
<mat-datepicker #publishdate></mat-datepicker>
</mat-form-field>
I used [min]="startDate.value" and worked like expected (disabled endDate calendar previous dates from selected date in startDate Calendar)
Latest version accept minDate and maxDate as Properties
https://material.angular.io/components/datepicker/api
<mat-calendar [minDate]="theDateYouWant"></mat-calendar>
<mat-form-field >
<input placeholder="Enter Date" matInput
[matDatepicker]="picker1"
formControlName="voucherExpirationDate"
[min]="minDate">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
first date
<mat-form-field appearance="outline" class="w-100">
<mat-label>1st installment date</mat-label>
<input matInput [matDatepicker]="firstDate (focus)="firstDate.open()"
placeholder="Select 1st installment date"
formControlName="fstInstalmentDate" readonly required>
<mat-datepicker-toggle matSuffix [for]="firstDate"></mat-datepicker-toggle>
<mat-datepicker #firstDate></mat-datepicker>
</mat-form-field>
2nd date
<mat-form-field appearance="outline" class="w-100">
<mat-label>2nd installment date</mat-label>
<input matInput [matDatepicker]="secondDate" (focus)="secondDate.open()"
placeholder="Select 2nd installment date"
[min]="settingForm?.get('fstInstalmentDate')?.value"
formControlName="scndInstalmentDate" readonly required>
<mat-datepicker-toggle matSuffix [for]="secondDate"></mat-datepicker-toggle>
<mat-datepicker #secondDate></mat-datepicker>
</mat-form-field>
Here settingForm is my formgroup name, Just one line change in second date no need to write anything in .ts file
//today's date in your component.ts file declare varaible which stores present //date
presentDate:Date = new Date();
//and in component.html write [min]= "presentDate" in input of type date
<input matInput [matDatepicker]="picker" [min]="presentDate" placeholder="Appointment date" formControlName="appointment_date">
<mat-datepicker-toggle matSuffix [for]="picker">
<mat-datepicker #picker>