【问题标题】:How to do Dropdown list Integration for countries and cities in Angular 5?如何在Angular 5中为国家和城市进行下拉列表集成?
【发布时间】:2018-12-11 16:09:25
【问题描述】:

我是 Angular 的新手。我想知道如何在 Angular 5 中对国家和州进行下拉集成。我只想在指定国家/地区时在下拉列表中看到特定的城市

【问题讨论】:

    标签: html angular typescript drop-down-menu angular5


    【解决方案1】:

    首先创建一个包含国家和城市的数据集。

    import { Component,OnInit } from '@angular/core';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
     import { FormBuilder, FormGroup } from '@angular/forms';
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  implements OnInit {
      policyForm: FormGroup;
      countries:Array<any> = [];
      cities:Array<any> = [];
      filteredCities: Array<any> = [];
      constructor(private fb: FormBuilder) {
       }
    
       ngOnInit() {
         this.countries = [{
              "name": "India",
              "code": "IN"
            },
            {
              "name": "United Kingdom",
              "code": "UK"
            }];
        this.cities = [{
              "name": "Mumbai",
              "country": "IN",
              "code": "MB"
            },
            {
              "name": "Delhi",
              "country": "IN",
              "code": "DL"
            },
            {
              "name": "London",
              "country": "UK",
              "code": "LON"
            },
            {
              "name": "Crowly",
              "country": "UK",
              "code": "CRL"
            }];
        this.createForm();
        this.policyForm.valueChanges.subscribe(
          (data) => {
            if (JSON.stringify(data) !== JSON.stringify({})) {
               if(data.country){
                this.filteredCities = this.cities.filter(city=>city.country===data.country.code);
           //     steps.filter(step => step.id === stepId)
              }
            }
          });
      }
    
      createForm() {
        this.policyForm = this.fb.group({
          country:[],
          city:[]
        });
      }
    
    }
    

    html

    <select style="width:100%" formControlName="country">
                <option *ngFor="let country of countries" [ngValue]="country">{{country?.name}}</option>
            </select>
    
         <select style="width:100%" formControlName="city">
          <option *ngFor="let city of filteredCities"  [ngValue]="city">{{city?.name}}</option>
            </select>
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2020-08-27
      • 2011-01-07
      • 2012-03-16
      • 2017-10-20
      相关资源
      最近更新 更多