1

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.

  • Well, nothing happens when I click Run code snippet, because Angular is not imported, and there is no `dtInitial` or `dtFinal` properties for `ngModel` to work off of. Please show more of your code. You need not use the Stack Snippet functionality if the code is not runnable. โ€“ Heretic Monkey Apr 06 '21 at 19:21
  • @HereticMonkey, I changed Stack Snippet to code. Thanks for the feedback. โ€“ Emerson Jahn Apr 06 '21 at 19:50

1 Answers1

-1

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 :)

XRaycat
  • 1,051
  • 3
  • 16
  • 28