【问题标题】:Angular2 select issueAngular2选择问题
【发布时间】:2016-04-23 08:51:09
【问题描述】:

以下代码用于 Angular 2 beta 13

<select (change)="handleChange($event)">
    <option value="">-- please choose an option --</option>
    <option *ngFor="#option of options" [value]="option.id">{{ option.name }}</option>
</select>

options 数组可以像[{id: 0, name="First"}, {id: 1, name="Second"}] 一样简单。我的意思是,当做出新的选择时,我能够获得所选选项的值。现在该值与标签相同(选项的innerText)。

现在,在测试版 1415 中,相同的代码不再起作用。这是 Angular 2 的一个错误,还是我需要在我自己的代码中引入的重大更改?

【问题讨论】:

    标签: angular angular2-template angular2-directives


    【解决方案1】:

    你可以

    • 通过在options by id 中查找分配给选项的值

    • 或者使用[ngValue](在beta.15中引入)直接使用对象值

    @Component({
        selector: 'my-app',
        template: `
        <div>selected: {{selected1 | json}}</div>
        <select (change)="handleChange($event)">
          <option value="">-- please choose an option --</option>
          <option *ngFor="#option of options" [value]="option.id">{{ option.name }}</option>
        </select>    
    
        <div>selected: {{selected2 | json}}</div>
        <select [(ngModel)]="selected2">
          <option value="">-- please choose an option --</option>
          <option *ngFor="#option of options" [ngValue]="option">{{ option.name }}</option>
        </select>`
    })
    export class AppComponent {
      options = [{id: 0, name:"First"}, {id: 1, name:"Second"}];
      selected1;
      selected2 = "";
    
      handleChange(event) {
        console.log(event.target.value);
        this.selected1 = this.options.filter((option) => {
          return option.id == event.target.value;
        })[0];    
    
      }
    }
    

    Plunker examplebeta.16

    【讨论】:

      【解决方案2】:

      是的,即使我之前也遇到过。我将[value] 更改为[attr.value] 并开始工作。 我希望它也对你有用..

      查看 beta 14 和 15 here 中的其他更改

      【讨论】:

      • attr.value 表示属性绑定,我认为这与选择/选项无关
      • 即使我们在这里绑定属性,也不会影响我的功能。对吗?
      • 为什么要添加这个属性绑定?如果它根本没有影响
      • 好的,那么我可以在select中使用[ngModel]而不是在option中绑定value属性吗?
      • 我不知道这个
      【解决方案3】:

      我猜你只想要handleChange() 方法中的id

      你如何在你的方法中访问id

      试试这个:

      handleChange(evt) {
          let id = (<HTMLInputElement>event.target).value;
      }
      

      $event 对象的形状由引发事件的任何因素决定。事件来自 DOM,所以$event 必须是标准的 DOM 事件对象。 $event.target 给了我们一个 HTMLInputElement,它有一个包含 id 的 value 属性。

      See also Angular Docu

      【讨论】:

      • 我想我一定是做错了什么,现在看来工作正常。我确实使用(&lt;HTMLInputElement&gt;event.target).value 来获得价值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2017-01-16
      • 2011-11-09
      • 1970-01-01
      • 2018-08-25
      相关资源
      最近更新 更多