简体   繁体   English

如何在没有双向数据绑定的情况下从Angular2中的“选择”中获取所选对象

[英]How to get selected object from “Select” in Angular2 without two-way data binding

I'm trying to create a dropdown with a list of objects. 我正在尝试使用对象列表创建一个下拉列表。 Due to the dropdown including other options it cannot be two-way binded to an array. 由于下拉列表包括其他选项,因此无法与阵列进行双向绑定。 On selection I want to pass the object to the component, but currently I can only pass the display value. 在选择时我想将对象传递给组件,但是目前我只能传递显示值。

Here is my template: 这是我的模板:

    <select (change)="doSomething($event.target.value)">
        <option disabled selected>Please select...</option>
        <option *ngFor="let item of items" [ngValue]="item">{{ item.description }}</option>
        <option [ngValue]="">None of the above</option>
    </select>

And function in the component: 并且组件中的功能:

    doSomething(item) {
        console.log(item);
    }

This results in "Item description", rather than {'id': 4, .... how can I change this? 这导致“项目描述”,而不是{'id':4,......我怎么能改变这个?

<select [(ngModel)]="selectedValue" (change)="doSomething()">
    <option disabled selected>Please select...</option>
    <option *ngFor="let item of items" [ngValue]="item">{{ item.description }}</option>
    <option [ngValue]="">None of the above</option>
</select>

selectedValue: any;
doSomething() {
    console.log(this.selectedValue);
}

You can try with this idea. 你可以尝试这个想法。

The [(ngModel)] attribute is shortcut of [ngModel] and (ngModelChange) . [(ngModel)]属性是[ngModel](ngModelChange)快捷方式。

Example

[(ngModel)]="foo"

Is equivalent to 相当于

[ngModel]="foo" (ngModelChange)="foo = $event"

Note that $event is the change emitted from the component. 请注意, $event是从组件发出的更改。

So in your case, you want to do something on (ngModelChange) 所以在你的情况下,你想做什么(ngModelChange)

component.html component.html

(ngModelChange)="doSomething($event)"

component.ts component.ts

doSomething(value) {

    console.log(value)

    // If you want to manually "re-bind" the model,
    // you can re-assign it, this will make sure the ui
    // is updated with the new value
    this.foo = value
}
 <select #categoriesCtrl (change)='SelectedValue = categoriesCtrl.value'>
        <option *ngFor="#category of categories" [value]="category.id">{{category.name}}</option>
      </select>
      <button (click)="getValueFromSelect()">Get value</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM