如何为Angular 5中的国家和城市添加下拉列表集成?

时间:2018-07-03 11:02:11

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

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

1 个答案:

答案 0 :(得分:0)

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

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