Emerson Jahn
Emerson Jahn

Reputation: 21

Angular: input type="date" with initial value

I have two inputs type="date" to filter the data by period. I would like to bring them with value already informed when loading the page.

First input with value Date() -7.

Second input with Date().

This is my angular code:

<input type="date" class="form-control form-date" [(ngModel)]="dtInitial">       
<input type="date" class="form-control form-date" [(ngModel)]="dtFinal">´

Since now, thank you who can help me.

Upvotes: 1

Views: 2565

Answers (1)

XRaycat
XRaycat

Reputation: 1140

Your input should take in a string. Try to convert the date to a string in the component.

@Component({
  selector: "example",
  templateUrl: "./app.component.html",
  providers: [DatePipe]
})
export class AppComponent implements OnInit {
  dtInitial: string = "";
  dtFinal: string = "";

  constructor(private datePipe: DatePipe) {}

  ngOnInit(): void {
    let today: Date = new Date();
    let sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(today.getDate()-7)
    this.dtInitial = this.datePipe.transform(today, "yyyy-MM-dd");
    this.dtFinal = this.datePipe.transform(sevenDaysAgo, "yyyy-MM-dd");
 }
}

Alternatively, you could also use the datePipe directly in the template. You can format your date in other ways. Here you see some diffferent formats you can use: https://developer.mozilla.org/en-US/docs/Web/HTML/Date_and_time_formats#format_of_a_valid_date_string.

If you want to make the inputs update when one of them is changed you could add this to the component.

 updateDateInitial() {
   let newDate = new Date(this.dtInitial);
   newDate.setDate(newDate.getDate()-7)
   this.dtFinal = this.datePipe.transform(newDate, "yyyy-MM-dd");
 }

 updateDateFinal() {
    let newDate = new Date(this.dtInitial);
    newDate.setDate(newDate.getDate()+7)
    this.dtInitial = this.datePipe.transform(newDate, "yyyy-MM-dd");
 }

and this for the inputs.

<input (change)="updateDateInitial()" type="date" class="form-control form-date" [(ngModel)]="dtInitial">       
<input (change)="updateDateFinal()" type="date" class="form-control form-date" [(ngModel)]="dtFinal">

That how you could do it - but in general, you should consider if two-binding is the way to go :)

Upvotes: -1

Related Questions