You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中使用Filter方法实现下拉选框筛选展示选课学生列表

Solution: Filter Students by Selected Course in Angular

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 the allStudents array and returns only entries where the student's course matches the selected full course name.
  • The courseMap object 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 showStudents array—feel free to change this to this.showStudents = this.allStudents if you want to display all students by default.

内容的提问来源于stack exchange,提问作者Aman Solanki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:09:24