Angular 12.2.4中如何从mat-datepicker获取yyyy-MM-ddTHH24:mm:ss格式日期并传递给API
Hey there! Let's walk through how to get the selected date from your mat-datepicker, format it correctly, and pass it to your API. Here's a step-by-step solution tailored to your Angular 12 setup:
Step 1: Add Two-Way Binding to the Datepicker
First, we'll bind the datepicker's selected value to a variable in your component using [(ngModel)]. This lets us automatically capture the user's selected date.
Update your app.component.html:
<div> <mat-form-field> <input matInput [matDatepicker]="datepicker" placeholder="Tarih giriniz" [(ngModel)]="selectedDate" /> <!-- Add this binding --> <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle> <mat-datepicker #datepicker></mat-datepicker> </mat-form-field> </div> <div class="row"> <div class="col-sm"> <!-- Add click event to trigger API call --> <a role="button" class="btn btn-secondary" (click)="fetchGoldPrices()"> Göster </a> </div> </div>
Step 2: Update Your Component Logic
Next, we'll define the selectedDate variable, use Angular's DatePipe to format the date, and modify your API call to use the user-selected value.
Update your app.component.ts:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DatePipe } from '@angular/common'; // Import DatePipe for formatting export class AppComponent implements OnInit { goldPrices: any[] = []; selectedDate: Date | null = null; // Variable to hold selected date constructor( private httpClient: HttpClient, private datePipe: DatePipe // Inject DatePipe ) {} ngOnInit(): void { // Remove the hardcoded call here—we'll trigger it on button click instead } // Method to handle button click and API call fetchGoldPrices(): void { // Guard clause: Don't proceed if no date is selected if (!this.selectedDate) { alert('Lütfen bir tarih seçiniz!'); return; } // Format date to yyyy-MM-dd (matches what your API accepts) const formattedDate = this.datePipe.transform(this.selectedDate, 'yyyy-MM-dd'); if (formattedDate) { this.getGoldPrices(formattedDate); } } getGoldPrices(dateString: string): void { this.httpClient.get<any>(`http://localhost:55000/api/GoldPriceDetail/${dateString}`) .subscribe( response => { console.log(response); this.goldPrices = response; }, error => { console.error('API çağrısı başarısız oldu:', error); } ); } }
Step 3: Ensure Required Modules Are Imported
Make sure your AppModule includes all necessary modules for ngModel, DatePipe, and Angular Material components:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Required for ngModel import { CommonModule } from '@angular/common'; // Required for DatePipe import { HttpClientModule } from '@angular/common/http'; // Angular Material Modules import { MatDatepickerModule } from '@angular/material/datepicker'; import { MatInputModule } from '@angular/material/input'; import { MatNativeDateModule } from '@angular/material/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, FormsModule, CommonModule, HttpClientModule, MatDatepickerModule, MatInputModule, MatNativeDateModule ], providers: [DatePipe], // Register DatePipe as a provider bootstrap: [AppComponent] }) export class AppModule { }
Key Notes:
- Two-Way Binding:
[(ngModel)]keeps your component'sselectedDatevariable synced with the datepicker's value. - Date Formatting:
DatePipehandles converting theDateobject to theyyyy-MM-ddstring format your API expects. If you ever need the fullyyyy-MM-ddTHH:mm:ssformat later, just change the format string to'yyyy-MM-ddTHH:mm:ss'. - User Experience: The guard clause checks if a date is selected before making the API call, preventing invalid requests.
- Error Handling: Added an error callback to the
subscribemethod to log API failures (you can replace this with a user-friendly message if needed).
内容的提问来源于stack exchange,提问作者Aysenur

