Angular 14中如何通过forEach与Input装饰器为下拉框正确传值?
问题解决:下拉框重复加载并显示对应类型数据
当前问题是每个下拉框重复加载所有数据,原因是父组件遍历vehicle数组时,给每个app-vehicle组件传入了完整的travals数组,未做类型过滤。
解决步骤:
修改父组件模板,传递当前车辆类型
在*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>子组件接收类型并过滤数据
在子组件中添加输入属性接收车辆类型,通过计算属性过滤出对应类型的数据: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); } }子组件模板渲染过滤后的数据
在子组件的下拉框中,遍历过滤后的数组生成选项:<select> <option *ngFor="let item of filteredVehicles" [value]="item.value"> {{ item.name }} </option> </select>
修改完成后,每个下拉框将仅显示对应类型的车辆数据,不会重复加载所有内容。
内容的提问来源于stack exchange,提问作者EMahan K
相关产品推荐
相关产品推荐

