在Angular2的``选择''列表中设置最初选择的项目 [英] Set initially selected item in Select list in Angular2

查看:80
本文介绍了在Angular2的``选择''列表中设置最初选择的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保存,我设法获得了一个与我的模型绑定的选择"列表,但是如果我提供编辑功能,我将无法确定如何使Angular2在选择"列表上自动选择正确的选项.换句话说,如果我正在通过表单编辑现有对象,则需要选择"列表以反映对象的初始状态(例如,选择"列表中的选项5),而不是仅将其默认为第一项

I've managed to get a Select list to bind with my model for the purpose of saving, but I cannot work out how to make Angular2 automatically select the correct option on the Select list if I'm providing editing functionality. In other words, if I'm editing a pre-existing object via a form, I need the Select list to reflect the initial state of the object (e.g. option 5 in the select list), rather than it just defaulting to the first item.

<select [ngModel]="originalObject">
    <option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>

我以为它应该起作用,但是不起作用!

How I imagine it should work, but doesn't!

<select [ngModel]="originalObject">
    <option *ngFor="let object of objects" [ngValue]="object" [selected]="object === originalObject">{{object.name}}</option>
</select>

所以从本质上讲,我正在尝试使用option的"selected"属性,但是由于某种原因它什么也没做.在这种情况下,"selectedObject"将是它可以读取的组件中的对象.

So essentially I'm trying to make use of the 'selected' property on option, but for whatever reason it doesn't do anything. The 'selectedObject' in this case would be an object in the component that it can read.

推荐答案

好的,所以我弄清楚了问题所在以及我认为最有效的方法.就我而言,因为从Java脚本角度来看这两个对象并不相同,例如:它们可能共享相同的值,但是它们是不同的实际对象,例如originalObject完全与objects完全实例化,而objects本质上是参考数据数组(用于填充下拉列表).

Okay, so I figured out what the problem was, and the approach I believe works best. In my case, because the two objects weren't identical from a Javascript perspective, as in: they may have shared the same values, but they were different actual objects, e.g. originalObject was instantiated entirely separately from objects which was essentially an array of reference data (to populate the dropdown).

我发现最适合我的方法是比较对象的唯一属性,而不是直接比较两个完整的对象.此比较是在绑定属性selected中完成的:

I found that the approach that worked best for me was to compare a unique property of the objects, rather than directly compare the two entire objects. This comparison is done in the bound property selected:

<select [ngModel]="originalObject">
    <option *ngFor="let object of objects" [ngValue]="object" [selected]="object.uniqueId === originalObject.uniqueId">{{object.name}}</option>
</select>

这篇关于在Angular2的``选择''列表中设置最初选择的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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