【问题标题】:Angular - I am trying to populate and select from dropdown menu from array object valuesAngular - 我正在尝试从数组对象值的下拉菜单中填充和选择
【发布时间】:2021-12-03 10:43:35
【问题描述】:

我在下拉列表和数组对象中遇到了一些问题。

我正在尝试从下拉菜单中选择值,但现在数组值未填充到下拉菜单中。

我没有得到什么是错误。

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    
constructor(private title: Title) {}

    ngOnInit() {
        this.title.setTitle('Select through Dropdown');
    }
    
    selectedCity: String = "--Choose City--";
  
    City: Array<any> = [
        // City=[
        { 
            name: 'India',
            states: 
            [ 
                { 
                    name: 'Karnataka', 
                    
                    cities: ['Bangalore', 'Gulbarga', 'Thumkur', 'Coorg' ]

                } , 
                { 
                    name: 'Andhrapradesh',
                    cities: [ 'hyderabadh', 'x', 'Y', 'Z' ] 
                }
            ] 
        },
        
        {   
            name: 'USA',
            states:
            [
                { 
                    stname: 'California',
                    cities: [ 'Los Angeles', 'San Francisco' ]
                }, 
                
                { 
                    stname: 'Texas', 
                    cities: [ 'Houston', 'Dallas' ] 
                } 
            ] 
        },
    ];
    

    selected = "----"

    changecities(city: any){
        this.selected = city.target.value

        console.log (this.selectedCity );
    }
    
}

app.component.html

<div class="content" style="background-color: rgb(196, 195, 195);">
    <h2 style="text-align: center;">Select Your Choices</h2>

    <div class="card-container" style="padding-bottom: 2em; padding-left: 10em;">
        <label>City : </label>
            <select placeholder="City" [(ngModel)]="selectedCity" (change)="changecities($event)">
            <option>--Choose City--</option>
            <option *ngFor="let city of City" >
                {{city.cities}}
            </option>
        </select>
    </div>
    <p>You selected {{selected}}</p>    
</div>

<router-outlet></router-outlet>

我无法在下拉菜单中访问城市的值。

如何解决这个问题,谢谢

【问题讨论】:

  • 您想访问哪些城市?您的数据中有多个国家/地区的城市
  • @AT82 我想在一个下拉菜单中访问所有城市

标签: angular drop-down-menu arrayobject arrayofarrays


【解决方案1】:

如果您想在一个下拉列表中显示来自所有国家/地区的所有城市,我想将您拥有的数组展平为字符串数组,而不是在模板中显示,所以您可以做的是声明一个新变量,例如cities,然后映射和展平数据:

this.cities = this.City.map(x => x.states.map(y => y.cities)).flat(2)

然后在模板中:

<option *ngFor="let city of cities">
  {{ city }}
</option>

STACKBLITZ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 2021-09-18
    • 2022-11-17
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多