我正在使用Reactive表单,我有一个级联下拉列表,如果用户在第一页中选择了一个现有项目(此页面中有此问题),则该下拉列表可以具有默认值,如果用户要创建一个项目,则该下拉列表可以没有任何价值。
所以这是问题所在:
当用户来自现有项目时,会选择价格表,但似乎没有任何价值,因为未显示货币。当我再次按预期选择自动选择货币的价目表时,有人对此有解决办法吗?提前致谢。
这是代码示例,谢谢您的时间
JSON(从pageChanged()返回)
Component.ts(自动选择值)
pageChanged(event){
const current = this.currentPage = event;
return this.httpClient.get<QuotationsInterface>(`this.url${this.projectId}?page=${current}&token=${this.token.token}`)
.subscribe(
data => {
console.log('GET PROJECT BY ID OK',data);
this.project = data.project;
this.registerForm.controls['pricelist'].setValue(this.project.pricelist_id);
this.registerForm.controls['currency'].setValue(this.project.currency_id);
},
error => {
console.log("PAGE PROJECT FAILED", error)
}
)
}
Component.html
<div class="flex2 pl10" (change)="selectedPriceListIndex = $event.target.selectedIndex-1">
<select formControlName="pricelist" class="form-control" [ngClass]="{'is-invalid': submitted && f.pricelist.errors}" >
<option value="" disabled selected>Select a Pricelist</option>
<option *ngFor="let p of filter.ListPricelist;let i = index;" [ngValue]="p.id" id="pricelist_id" >{{i}} {{p.label}}</option>
</select>
<div *ngIf="submitted && f.pricelist.errors" class="invalid-feedback">
<div *ngIf="f.pricelist.errors.required">Pricelist is required</div>
</div>
</div>
<div class="flex2 pl10">
<select formControlName="currency" [ngClass]="{'is-invalid': submitted && f.currency.errors}" class="form-control">
<option value >Select a currency</option>
<option *ngFor="let c of filter.ListPricelist[selectedPriceListIndex]?.currencies" [ngValue]="c.id" selected="selected">{{c.code}}</option>
</select>
<div *ngIf="submitted && f.currency.errors" class="invalid-feedback">
<div *ngIf="f.currency.errors.required">Currency is required</div>
</div>
</div>
编辑:
谢谢大家的回答,我通过使用.patchValue(请检查@nima_amr answer)并替换为component.html
<option *ngFor="let c of filter.ListPricelist[selectedPriceListIndex]?.currencies" [ngValue]="c.id" selected="selected">{{c.code}}</option>
通过以下方式:
<option *ngFor="let c of filter.ListPricelist[registerForm.value.pricelist-1]?.currencies" [value]="c.id">{{c.code}}</option>
您可以将.setValue替换为.patchValue,例如Down
pageChanged(event){
const current = this.currentPage = event;
return this.httpClient.get<QuotationsInterface>(`this.url${this.projectId}?page=${current}&token=${this.token.token}`)
.subscribe(
data => {
console.log('GET PROJECT BY ID OK',data);
this.project = data.project;
this.registerForm.patchValue({
pricelist: this.project.pricelist_id,
currency: this.project.currency_id
});
},
error => {
console.log("PAGE PROJECT FAILED", error)
}
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句