Angular 4选择在模型中给出时不能正常工作?

Abh*_*nth 8 html5 typescript angular

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

没有ngModel

<select class="form-control">
    <option *ngFor="let type of ListType" [value]="type .id">{{type .name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述


使用ngModel

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

在此输入图像描述

这是显示为空.

方法尝试:

  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. 甚至尝试通过模型设置所选值仍然没有结果.

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

AJT*_*T82 9

您正在定义值select作为id值,而您正在selectedListType使用name属性.所以你要做的就是提供idselectedListType,例如,如果你ListType看起来像这样:

[{id:1, name: 'Dislike'},{...}]
Run Code Online (Sandbox Code Playgroud)

你想将selectedListyType值设置为1.其他选项是,如果你不知道你可以做的id值:

ngOnInit() {
  this.selectedListType = this.ListType.find(x => x.name === 'Dislike').id
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 欢迎你,很高兴我能提供帮助!:) (2认同)