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

Angular 14中如何在各下拉框中展示对象数组值

实现多下拉框展示对应车辆类型的选项

核心实现思路

通过父组件循环车辆类型列表,动态给子组件传入对应类型的数组数据,子组件负责渲染下拉框展示选项。


步骤1:完善子组件(VehicleComponent)

首先给子组件添加下拉框模板,同时优化类型定义增强代码健壮性:

vehicle.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-vehicle',
  templateUrl: './vehicle.component.html'
})
export class VehicleComponent implements OnInit {
  @Input() data: string[] = []; // 明确类型为字符串数组
  constructor() {} 
  ngOnInit() {
    console.log(this.data);
  }
}

vehicle.component.html

<select>
  <option value="" disabled selected>请选择评价</option>
  <option *ngFor="let item of data" [value]="item">{{ item }}</option>
</select>

步骤2:父组件(MainComponent)动态传递数据

在父组件模板中循环车辆类型列表,将对应类型的数组传给子组件:

main.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html'
})
export class MainComponent implements OnInit {
  travals = {
    Car: ['Good', 'Bad'],
    Bus: ['Super', 'Cool'],
    Cycle: ['Small', 'Big'],
    MotorCycle: ['Too Big', 'Scooty'],
    Train: ['Special', 'Normal', 'Super Fast'],
  };

  vehicle = ['Car', 'Bus', 'Cycle', 'MotorCycle', 'Train']; 
  constructor() {} 
  ngOnInit() {}
}

main.component.html

<div *ngFor="let type of vehicle" style="margin: 10px 0;">
  <label>{{ type }} 评价:</label>
  <app-vehicle [data]="travals[type]"></app-vehicle>
</div>

实现说明

  1. 父组件通过*ngFor遍历vehicle数组,动态生成与车辆类型数量一致的子组件
  2. 利用对象属性访问语法travals[type],精准获取当前类型对应的评价数组,通过@Input()传递给子组件
  3. 子组件接收数据后,再次用*ngFor渲染下拉框选项,完成每个下拉框对应不同车辆类型的需求

内容的提问来源于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.24 23:33:22