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

Angular 14中如何通过forEach与Input装饰器为下拉框正确传值?

问题解决:下拉框重复加载并显示对应类型数据

当前问题是每个下拉框重复加载所有数据,原因是父组件遍历vehicle数组时,给每个app-vehicle组件传入了完整的travals数组,未做类型过滤。

解决步骤:

  1. 修改父组件模板,传递当前车辆类型
    在*ngFor循环中,把当前的车辆类型v作为输入参数传给子组件:

    <div
      class="custom-select"
      style="width:400px;"
      *ngFor="let v of vehicle; index as i"
    >
      <p>{{ v }}</p>
      <app-vehicle [data]="travals" [vehicleType]="v"></app-vehicle>
    </div>
    
  2. 子组件接收类型并过滤数据
    在子组件中添加输入属性接收车辆类型,通过计算属性过滤出对应类型的数据:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-vehicle',
      templateUrl: './vehicle.component.html',
      styleUrls: ['./vehicle.component.css']
    })
    export class VehicleComponent {
      @Input() data: any[] = [];
      @Input() vehicleType: string = '';
    
      get filteredVehicles() {
        return this.data.filter(item => item.type === this.vehicleType);
      }
    }
    
  3. 子组件模板渲染过滤后的数据
    在子组件的下拉框中,遍历过滤后的数组生成选项:

    <select>
      <option *ngFor="let item of filteredVehicles" [value]="item.value">
        {{ item.name }}
      </option>
    </select>
    

修改完成后,每个下拉框将仅显示对应类型的车辆数据,不会重复加载所有内容。

内容的提问来源于stack exchange,提问作者EMahan K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:27:20