无法将值设置回页面加载时的角度选择下拉列表



Hello Angular Champs,

我有一个下拉列表,我可以将所选的dorp down值保存在会话存储中。在加载该组件时,无法在下拉列表中选择该值。

html代码

<div>
<div>
<select id="customer_slct" #customerSelected>
<option value="{{customer.customerId}}" *ngFor="let customer of customerList">{{customer.name}} 
</option>
</select>
</div>
<div>
<button type="button" id="refreshCust" (click)="changeCustomer(customerSelected.value)">Refresh Customer<button>
</div>
</div>

组件ts文件。

ngOnInit(){
this.selectedCustomer = sessionStorage.getItem("selectedCustomer");
$('#customerSelected').val(this.selectedCustomer);//This didnt work. 
//I need to selected customer number in the dropdown which was selected be4 page refresh.
}
changeCustomer(newCustomer:string){
sessionStorage.setItem("selectedCustomer",newCustomer);
window.location.reload();//I want to reload all componenets with new customer details.
}
<div>
<div>
<select id="customer_slct" #customerSelected [(ngModel)]="selectedCustomer">
<option value="{{customer.customerId}}" *ngFor="let customer of customerList">{{customer.name}} 
</option>
</select>
</div>
<div>
<button type="button" id="refreshCust" (click)="changeCustomer(customerSelected.value)">Refresh Customer<button>
</div>
</div>

组件ts文件。

ngOnInit(){
this.selectedCustomer = sessionStorage.getItem("selectedCustomer");
}
changeCustomer(newCustomer:string){
sessionStorage.setItem("selectedCustomer",newCustomer);
window.location.reload();//I want to reload all componenets with new customer details.
}

正如注释中所讨论的,您应该为应用程序使用双向数据绑定,这是理想的解决方案。

只是告诉你,你的代码中的问题是你使用了错误的标识符来按ID选择元素。你需要使用这行:

$('#customer_slct').val(this.selectedCustomer);

最新更新