Angular 4 Selected 在模型中给出时无法正常工作?

新手上路,请多包涵

当我尝试提供下拉菜单时。默认情况下,我需要选择一个需要显示的值。当我不使用 ngModel 时,我可以显示默认值。

没有 ngModel

 <select class="form-control">
    <option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>

上面的代码在我们编译时工作正常。我能够在要显示的列表中看到第一个值。

在此处输入图像描述


使用 ngModel

 <select class="form-control" [(ngModel)]="selectedListType">
    <option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>

在此处输入图像描述

这是显示为空。

尝试过的方法:

  1. 二手 已选

<option *ngFor="let type of ListType" [selected]="type.name === 'Dislike'" [value]="type .id">{{type .name}}</option>

  1. 使用的属性。已选择

<option *ngFor="let type of ListType" [ngValue]="type " [attr.selected]="type .name== type.name ? true : null">{{ type.name }}</option>

编辑

  1. 即使试图通过模型设置选定的值仍然没有结果。

还有其他方法吗?或者我做错了什么?

原文由 Abhishek Ekaanth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 282
2 个回答

You are defining the value for the select as the id value, whereas you are feeding the selectedListType with the name property.因此,您要做的是提供 id 的值 selectedListType ,例如,如果您的 ListType 看起来像这样:

 [{id:1, name: 'Dislike'},{...}]

您要将 selectedListyType 值设置为 1 。另一种选择是,如果您不知道您可以执行的 id 值:

 ngOnInit() {
  this.selectedListType = this.ListType.find(x => x.name === 'Dislike').id
}

然后您的模板将如下所示:

 <select class="form-control" [(ngModel)]="selectedListType">
  <option *ngFor="let type of ListType" [value]="type.id">{{type.name}}</option>
</select>

原文由 AT82 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试让你的价值和 ngModel 一样

value = {{type .id}}[(ngModel)]= "selectedListType.id"

并在 html 中选择后打印该值

<br>id is {{selectedListType.id}}

原文由 Hrishikesh Kale 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题