Angular 4选择在模型中给出时不能正常工作? [英] Angular 4 Selected not working properly when it is given in model?

查看:155
本文介绍了Angular 4选择在模型中给出时不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图给出一个下拉菜单时。默认情况下,我需要选择需要显示的值。当我没有使用ngModel时,我可以显示默认值。

When I'm trying to give a drop-down menu. By default, I need to select a value that needs to be displayed. When I'm not using a ngModel I'm able to display the default value.

没有ngModel

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

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

The Above code works fine when we compile it. I'm able to see first value on the list to be displayed.

使用ngModel

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

这是显示为空。

尝试的方法:


  1. used Selected

< option * ngFor =let List of ListType[selected] = type.name ==='不喜欢'[value] =type .id> {{type .name}}< / option>


  1. 使用attr.Selected

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

编辑


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

还有其他方法吗?

我做错了什么?

Is there any alternative way? Or Am I doing something wrong?

推荐答案

您正在定义<$ c的值$ c>选择作为 id 值,而您正在使用 selectedListType name property。所以你要做的是为 selectedListType 提供 id 值,例如你的 ListType 如下所示:

You are defining the value for the select as the id value, whereas you are feeding the selectedListType with the name property. So what you want to do is either provide the id value for selectedListType, so for example if your ListType looks like this:

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

您要设置 selectedListyType 值为 1 。其他选择是,如果你不知道你可以做的id值:

you want to set selectedListyType value as 1. Other option is, if you do not know the id value you can do:

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

,您的模板将如下所示:

and your template will then look like this:

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

这篇关于Angular 4选择在模型中给出时不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆