Angular 4中为搜索输入添加订单ID与创建日期过滤逻辑
Got it, let's get this sorted for you. Since you already have MomentJS set up in StackBlitz, here's how to modify your getTransactionNames private method to filter by both order ID and created date using the search input:
Step-by-Step Modification
First, I'll assume your search input value is stored in a variable (like this.searchTerm — adjust this to match your actual code). We'll add a filter condition that checks both the order ID and the formatted date against the search term:
private getTransactionNames() { // Normalize the search term to avoid case sensitivity and extra spaces const normalizedSearchTerm = this.searchTerm?.toLowerCase().trim() || ''; return this.transactions // First filter transactions that match either ID or date .filter(transaction => { // Format the date into a user-friendly string (adjust the format as needed) const formattedDate = moment(transaction.date).format('YYYY-MM-DD'); // Check if ID contains the search term (case-insensitive) const matchesId = transaction.id.toLowerCase().includes(normalizedSearchTerm); // Check if formatted date contains the search term const matchesDate = formattedDate.includes(normalizedSearchTerm); // Return all transactions if search term is empty, else return matches return normalizedSearchTerm === '' ? true : matchesId || matchesDate; }) // Keep your existing map logic here (the part starting with moment(v.date...) .map(transaction => `${transaction.id} - ${moment(transaction.date).format('YYYY-MM-DD')}`); }
Key Details Explained
- Normalized Search Term: Converting the search input to lowercase and trimming spaces ensures the filter works regardless of how the user types (e.g., "123" vs "123 " vs "123").
- Date Formatting: Using
moment(transaction.date).format('YYYY-MM-DD')converts the date into a string users are likely to search for (adjust the format string to match what makes sense for your users, likeMM/DD/YYYYif that's your locale). - Dual Filter Check: The
matchesId || matchesDatecondition means transactions will show up if either their ID contains the search term, or their formatted date does.
If You Already Have an Existing Filter
If your current code already has a filter for the order ID, simply replace that filter's condition with the logic above. For example, if you had:
return this.transactions .filter(v => v.id.includes(this.searchTerm)) .map((v) => moment(v.date)...
Update it to:
return this.transactions .filter(v => { const normalizedSearchTerm = this.searchTerm?.toLowerCase().trim() || ''; const formattedDate = moment(v.date).format('YYYY-MM-DD'); return normalizedSearchTerm === '' ? true : v.id.toLowerCase().includes(normalizedSearchTerm) || formattedDate.includes(normalizedSearchTerm); }) .map((v) => moment(v.date)... // Keep your original map logic here
This will make your search input work for both order IDs and created dates as requested!
内容的提问来源于stack exchange,提问作者graphicnerd

