如何在Angular中使用Filter方法实现下拉选框筛选展示选课学生列表
Got it, let's walk through how to make this course filter work properly using JavaScript's filter() method in your Angular component. Here's the step-by-step breakdown:
1. Update Your Component Class
First, make sure you have the required variables and the show() method implemented in your .ts file. We'll map the dropdown's short values to the full course names and filter the students accordingly:
import { Component } from '@angular/core'; interface Student { name: string; course: string; } @Component({ selector: 'app-student-filter', templateUrl: './student-filter.component.html', styleUrls: ['./student-filter.component.css'] }) export class StudentFilterComponent { allStudents: Student[] = [ {name:'James',course:'Angular'}, {name:'Kary',course:'Android'}, {name:'Bob',course:'Java'}, {name:'Pam',course:'Java'}, {name:'Steve',course:'Angular'}, {name:'Williams',course:'Android'}, {name:'Julis',course:'Angular'}, {name:'Matt',course:'Java'}, {name:'Willy',course:'Android'}, ]; crse: string = ''; // Holds the selected dropdown value showStudents: Student[] = []; // Holds filtered students show(): void { // Map dropdown short codes to full course names const courseMap: { [key: string]: string } = { 'ang': 'Angular', 'and': 'Android', 'java': 'Java' }; // Get the full course name based on selected value const selectedCourse = courseMap[this.crse]; // Filter students: if no course selected, show empty or all (your call) if (!selectedCourse) { this.showStudents = []; // Or set to this.allStudents to show everyone return; } // Use filter() to get students in the selected course this.showStudents = this.allStudents.filter(student => student.course === selectedCourse ); } }
2. Tweak the HTML Layout (Optional but Important)
Notice in your original HTML, the row displaying student data only has two col-4 divs, but the header row has three. This will cause layout misalignment. Let's fix that to match the header structure, plus adjust the event trigger for dropdowns:
<div class="container"> <div class="row"> <!-- Dropdown Column --> <div class="col-4"> <select class="form-control" [(ngModel)]="crse" (change)="show()"> <option value=''>Courses...</option> <option value="ang">Angular</option> <option value="and">Android</option> <option value="java">Java</option> </select> </div> <!-- Header Columns --> <div class="col-4 bg-dark text-light text-center">Name</div> <div class="col-4 bg-dark text-light text-center">Course</div> </div> <!-- Filtered Students Rows --> <div class="row" *ngFor="let st of showStudents"> <div class="col-4 border p-2"></div> <!-- Empty column to match dropdown position --> <div class="col-4 border p-2">{{st.name}}</div> <div class="col-4 border p-2">{{st.course}}</div> </div> </div>
I swapped (keyup) for (change) because dropdowns trigger change events when a selection is made, not keyup (that's for text input fields). This ensures the filter runs at the right time.
3. How It Works
- The
filter()method loops through theallStudentsarray and returns only entries where the student'scoursematches the selected full course name. - The
courseMapobject translates the dropdown's short values (like 'ang') to the full course names used in your student data, so the comparison is accurate. - When no course is selected, we clear the
showStudentsarray—feel free to change this tothis.showStudents = this.allStudentsif you want to display all students by default.
内容的提问来源于stack exchange,提问作者Aman Solanki

