angular 定义对象,将选择元素绑定到Angular中的对象

I'm new to Angular and trying to get up to speed with the new way of doing things.

I'd like to bind a select element to a list of objects -- which is easy enough:

@Component({

selector: 'myApp',

template: `

My Application

{{c.name}}

`

})

export class AppComponent{

countries = [

{id: 1, name: "United States"},

{id: 2, name: "Australia"}

{id: 3, name: "Canada"}

{id: 4, name: "Brazil"}

{id: 5, name: "England"}

];

selectedValue = null;

}

In this case, it appears that selectedValue would be a number -- the id of the selected item.

However, I'd actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:

{{c.name}}

but this does not seem to work. It seems to place an object in my selectedValue -- but not the object that I'm expecting. You can see this in my Plunker example.

I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated -- meaning I don't have access to the newly selected value at that point.

Is there a clean way to bind a select element to an object with Angular 2?

解决方案

My Application

{{c.name}}

NOTE: you can use [ngValue]="c" instead of [ngValue]="c.id" where c is the complete country object.

[value]="..." only supports string values

[ngValue]="..." supports any type

update

If the value is an object, the preselected instance needs to be identical with one of the values.

See also the recently added custom comparison https://github.com/angular/angular/issues/13268

available since 4.0.0-beta.7

Take care of if you want to access this within compareFn.

compareFn = this._compareFn.bind(this);

// or

// compareFn = (a, b) => this._compareFn(a, b);

_comareFn((a, b) {

if(this.x ...) {

...

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值