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

标签 html angular typescript

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

没有 ngModel

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

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

enter image description here


使用 ngModel

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

enter image description here

这是显示为空。

尝试过的方法:

  1. 使用精选

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

  1. 使用 attr.Selected

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

编辑

  1. 甚至尝试通过模型设置所选值仍然没有结果。

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

最佳答案

您正在将 select 的值定义为 id 值,而您正在为 selectedListType 提供 name 属性。因此,您要做的是为 selectedListType 提供 id 值,例如,如果您的 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>

关于html - Angular 4 Selected 在模型中给出时无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48003432/

相关文章:

html - 在 ng2-pdf-viewer Angular 上添加元素 <button>

html - 为什么 div 不包围它的 child ?

angular - 无法在 Angular 2 的 ErrorHandler 中定义带有参数的构造函数

html - CSS 媒体查询的精确 NOT(逆)

angular - 应如何使用 Angular 7 Material `panelClass` 属性?

angular - 从angular2应用程序调用在Docker容器中运行的服务

javascript - 安装本地 Node 类型时出现重复标识符

typescript - 将translateProvider.useLoader 与Typescript 结合使用

jquery - 如果引导列达到 12,如何在 jQuery 中添加类行?

javascript - 在 highcharts/highstock 中添加自定义下拉菜单