Angular中如何绑定日期范围单选框并动态展示提交表单列表
Let's walk through how to connect your radio group selection to fetching the correct form submissions based on the chosen date range. Here's a step-by-step implementation tailored to your Angular setup:
1. Update Your Component Class (TypeScript)
First, we'll handle the selection logic, date calculation, and API call in your component file:
import { Component } from '@angular/core'; import { FormService } from './path-to-your-form-service'; // Adjust this path to your actual service @Component({ selector: 'app-form-submissions', templateUrl: './form-submissions.component.html', styleUrls: ['./form-submissions.component.css'] }) export class FormSubmissionsComponent { // Bound to the radio group via ngModel selected: string = '1'; // Default to "Last 7 Days" for better UX formSubmissions: any[] = []; // Stores the fetched submission data constructor(private formService: FormService) {} // Triggered when the "GetFormSubmissions" button is clicked onGetFormSubmissions(): void { // Map radio selection to the number of days to subtract const daysToSubtract = this.getDaysFromSelection(); // Calculate the start and end dates for the range const endDate = new Date(); const startDate = new Date(); startDate.setDate(endDate.getDate() - daysToSubtract); // Format dates to match your API's expected format (e.g., YYYY-MM-DD) const formattedStart = this.formatDate(startDate); const formattedEnd = this.formatDate(endDate); // Fetch submissions from your backend service this.formService.getSubmissions(formattedStart, formattedEnd).subscribe({ next: (submissions) => { this.formSubmissions = submissions; // Update the list to display to users }, error: (error) => { console.error('Failed to fetch submissions:', error); // Add user-friendly error handling here (e.g., a toast or alert message) } }); } // Helper to convert radio selection to days private getDaysFromSelection(): number { switch(this.selected) { case '2': return 15; case '3': return 30; default: return 7; // Fallback to 7 days if no selection is made } } // Helper to format dates consistently for your API private formatDate(date: Date): string { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; } }
2. Update Your Template (HTML)
Modify your existing HTML to add the button click handler and display the fetched submissions:
<div class="col-lg-12" style="padding-top: 2px; padding-left: 18px"> <label id="example-radio-group-label" style="padding-right: 8px; font-weight: bold">Range Of Date :</label> <mat-radio-group aria-label="Select an option" [(ngModel)]="selected"> <mat-radio-button value="1" style="color: #1B4F58; font-weight: bold">Last 7 Days</mat-radio-button> <mat-radio-button value="2" style="color: #1B4F58; font-weight: bold">Last 15 Days</mat-radio-button> <mat-radio-button value="3" style="color: #1B4F58; font-weight: bold">Last 30 Days</mat-radio-button> </mat-radio-group> </div> <!-- Add your button with the click handler --> <button mat-raised-button color="primary" (click)="onGetFormSubmissions()">GetFormSubmissions</button> <!-- Display the fetched form submissions --> <div *ngIf="formSubmissions.length > 0" class="mt-3"> <h4>Submitted Forms</h4> <ul class="list-group"> <li class="list-group-item" *ngFor="let submission of formSubmissions"> {{ submission.formName }} </li> </ul> </div> <div *ngIf="formSubmissions.length === 0 && selected"> <p>No submissions found in the selected date range.</p> </div>
3. Key Implementation Notes
- Service Setup: Ensure your
FormServicehas agetSubmissionsmethod that accepts start and end dates and returns an Observable of submission data. Example:getSubmissions(startDate: string, endDate: string): Observable<any[]> { return this.http.get<any[]>(`/api/submissions?start=${startDate}&end=${endDate}`); } - Date Formatting: Adjust the
formatDatefunction to match the date format your backend expects (some APIs use ISO strings like2024-05-20T00:00:00Z). - Default Selection: We set
selected: string = '1'to default to "Last 7 Days"—you can remove this if you want users to explicitly select an option before fetching data (just add a check inonGetFormSubmissionsto handle unselected cases). - Error Handling: Extend the error block to show user feedback (like an Angular Material Snackbar) instead of just logging to the console.
内容的提问来源于stack exchange,提问作者shivam singh soryawanshi
相关产品推荐
相关产品推荐

