在angular4中根据国家名称填充citi名称?

时间:2018-05-02 09:44:15

标签: json angular angular5 angular4-httpclient

当我在下拉列表中点击国家/地区名称时,我希望在选择框中显示城市。我可以在第一个选择框中显示县,但第二个选择框显示为空。

我试过http ..我想要一个简单的方法。有人请帮忙。

这是我试过的......

json数据文件(file.json)

[
    {
        "countryName": "India",
        "cities": [
        {
            "id": 1,
            "name": "Banglaore",
            "founded": -200,
            "beautiful": true,
            "data": 123,
            "keywords": ["Kaveri", "River"]
        },
        {
            "id": 1,
            "name": "Pune",
            "founded": 0,
            "beautiful": false,
            "data": "no",
            "keywords": ["FSDF", "FS"]
        }
        ]
    },
    {
        "countryName": "US",
        "cities": [
        {
            "id": 2,
            "name": "CA",
            "founded": -200,
            "beautiful": true,
            "data": 123,
            "keywords": ["RT", "SSF"]
        },
        {
            "id": 2,
            "name": "NY",
            "founded": 0,
            "beautiful": false,
            "data": "no",
            "keywords": ["GSG", "DG"]
        }
        ]
    }
]

app.component.ts

import { Component } from '@angular/core';
import { Http,Response } from '@angular/http';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/filter';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private http: Http) { }
public myData;
public str1;

ngOnInit(){

 this.http.get("assets/file.json")
  .map((res:Response)=> res.json())
  .subscribe(data =>{this.myData = data})
}

app.component.html

<form name="countryForm">
    <select class="form-control" id="country" formControlName="country">
        <option value="default">--Select a country--</option>
        <option *ngFor="let d of myData" [value]="d"> {{d.countryName}} </option>
    </select>
    <select>
        <option value="0">--All--</option>
        <option *ngFor="let f of myData.cities">{{f.cities.name}}</option>
    </select>
</form>

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

 <form  name ="countryForm">
    <select #country class="form-control" id="country" formControlName="country">
        <option value="default">--Select a country--</option>
        <option *ngFor="let d of myData" [value]="d"> {{d.countryName}} </option>
    </select> 
  <select  >
     <option value="0">--All--</option>
     <option *ngFor="let city of country.value" [value]="city" >{{city.name}}</option>
  </select>
        </form>

检查类似问题的答案https://stackoverflow.com/a/50113538/9722237