我有两个<select>
元素,一个用于区域,另一个用于城市。我通过从getDistricts()
函数调用函数ngOnInit()
来获取区域。到目前为止一切都很好。
我不知道怎么告诉棱角分明将新城市带到城市。选择元素。我尝试在下面的代码中做,但我有一个错误:
ORIGINAL EXCEPTION: TypeError: Cannot read property 'cities' of undefined
当然,这是因为selectedDistrict
在开始时未定义。
这是一个区域对象的示例。 (它包括其中的城市)。
{
"id": 5,
"name": "A district",
"cities": [
{
"id": 59,
"name": "City 1"
},
{
"id": 60,
"name": "City 2"
}
]
},
district.service.ts:
import {Injectable} from "@angular/core";
import 'rxjs/add/operator/toPromise';
import {District} from "./district";
import {HttpClientService} from "../http-client/http-client.service";
@Injectable()
export class DistrictService {
private districtsUrl = 'districts/all';
constructor(private httpClient: HttpClientService) {
this.httpClient = httpClient;
}
getDistricts(): Promise<District[]> {
return this.httpClient.get(this.districtsUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
getDistrict(district: string): Promise<District> {
return this.getDistricts()[district];
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
视图-search.component.ts:
export class ViewSearchComponent implements OnInit {
districts: district[];
selectedDistrict: district;
constructor(private districtService: districtService) {}
ngOnInit() {
this.getDistricts();
}
getDistricts() {
return this.districtService.getDistricts().then(districts => this.districts = districts);
}
selectDistrict(district: district) {
this.selectedDistrict = district;
}
}
view.search.component.html
<select class="search-select">
<option *ngFor="let district of districts" (click)="selectDistrict(district)">
{{ district.name }}
</option>
</select>
<select class="search-select">
<option *ngFor="let city of selectedDistrict.cities ">
{{ city.name }}
</option>
</select>
答案 0 :(得分:1)
尝试初始化selectedDistrict: district;
selectedDistrict: district = {};
也可以选择一个选项我不认为这是一个好主意(click)="selectDistrict(district)"
,因为理论上你可以使用键盘/箭头来选择一个项目
所以你应该使用onchange
事件
<select (change)="alert(this.options[this.selectedIndex].text);">
答案 1 :(得分:1)
很少有人知道Angular2支持模板中的elvis运算符(即?),这对异步数据流非常有用。为此,您必须将模板更新为
<select class="search-select">
<option *ngFor="let city of selectedDistrict?.cities ">
{{ city.name }}
</option>
</select>
答案 2 :(得分:0)
尝试初始化区:district [];排列 你可以这样做:
districts = [];
问题是您正在尝试访问未初始化对象的城市属性。你需要确保你的区域对象被初始化。
例如使用新的
this.selectedDistrict = new District();
或
district = { "id": 5,
"name": "A district",
"cities": [
{
"id": 59,
"name": "City 1"
},
{
"id": 60,
"name": "City 2"
}
]}
也在此代码中
<select class="search-select">
<option *ngFor="let district of districts" (click)="selectDistrict(district)">
{{ district.name }}
</option>
</select>
确保正确调用selectDistrict
答案 3 :(得分:0)
我只需将* ngIf =“selectedDistrict”添加到我的selectedDistrict
元素,而不是初始化我的select
。