【发布时间】:2021-08-29 08:27:16
【问题描述】:
为了在用户填写地址信息时提供一个国家列表供用户选择。我设计了一个地址 ngForm 来收集地址。此外,该表单还适用于用户编辑他们的地址信息,这意味着如果地址存在,所有现有值将首先被修补。这意味着现有的地址元素,例如国家名称,将需要位于国家列表的顶部,或者只是从国家列表中选择一个作为默认值......也就是说,只要用户打开,用户所在的县就会显示他们的地址信息。他们还应该能够通过从列表中选择一个国家/地区来更改国家/地区。
使用下面的 html 和 ts 代码,我几乎无法将用户现有的国家/地区显示为默认值。
<form #addressForm="ngForm" (ngSubmit)="onSubmit(addressForm.value)">
<div class="d-flex justify-content-end mb-1">
<button [disabled]="!addressForm.valid || !addressForm.dirty" type="submit" class="btn btn-sm btn-primary">
<span style="font-size: 0.8em">Save Address</span>
</button>
</div>
......
<div class="form-row">
<div class="form-group col-md-4">
<label for="state">State/Province/Region:</label>
<select
id="state" class="form-control" name="State" [(ngModel)]="state">
<option *ngFor="let state of states let i = index"
[selected]="i === 0"
[ngValue]="state">{{state}}
</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="country">Country:</label>
<select
id="country" class="form-control" name="Country" [(ngModel)]="country"
(change)="onCountrySelected($event.target.value)">
<option *ngFor="let country of countries let i = index"
[selected]="i === 0"
[ngValue]="country">{{country}}
</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="zipcode">Zip Code:</label>
<input
......
</div>
</div>
</form>
组件.ts
getCountries() {
this.accountService.getUserAddress().subscribe((resp: IAddress) => {
this.address = resp;
if (this.address.country !== null)
{
this.memberService.getCountries().subscribe((resp: ICountry[]) => {
for (let country of resp)
{
this.countries.push(country.name);
}
this.countries = [this.address.country, ...this.countries];
this.states = [this.address.state, ...this.states];
});
} else {
this.memberService.getCountries().subscribe((resp: ICountry[]) => {
for (let country of resp)
{
this.countries.push(country.name);
}
this.countries = ['', ...this.countries];
}, error => {
console.log(error);
});
}
});
}
onCountrySelected(countryIdx: any) {
this.countryId = parseInt(countryIdx);
this.memberService.getStates(this.countryId).subscribe((resp: any[]) => {
this.states = [];
for (let state of resp)
{
this.states.push(state.name);
}
});
}
onSubmit(addressFormValues) {
console.log(addressFormValues);
this.accountService.updateUserAddress(addressFormValues).subscribe((address: IAddress) => {
this.toastr.success('Address saved');
}, error => {
this.toastr.error(error.message);
console.log(error);
});
}
另外,我也尝试分配从国家列表中获得的国家索引,以便直接选择一开始选择的国家。这似乎也不行。
<!-- begin snippet: js hide: false console: true babel: false -->
将html中选中的相应更改为:
<option *ngFor="let country of countries let i = index"
[selected]="i === countryIndex"
[ngValue]="country">{{country}}
</option>
我也尝试了 [selected]="address.country === country",但我仍然无法将用户现有的国家/地区值设为默认选择。 除了这个问题,所有采集到的地址数据都可以成功提交到后端。
【问题讨论】:
标签: html angular typescript default-value cascadingdropdown