0

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

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

我没有得到什么是错误。

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>

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

请问各位大佬怎么解决这个问题,谢谢

4

1 回答 1

0

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

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

然后在模板中:

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

堆栈闪电战

于 2021-12-03T13:14:14.347 回答