Angular2 ng For多个选择框。接下来选择获取值

时间:2016-11-09 09:55:24

标签: javascript arrays angular typescript

我创建了一个视图,在该视图中应该可以选择多个人。来自同一人名单。 (我不想使用多选)

我似乎没有得到:当在selectbox 1中选择一个值时,正在设置下一个选择框的值。为什么会这样?

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `
        <select *ngFor="let selectedPerson of selectedPeople; let i = index;" (change)="selectChanged(i, $event.target.value)">
            <option></option>
            <option *ngFor="let person of people" [value]="person.id">{{ person.name }}</option>
        </select>

        <pre>{{ people | json }}</pre>
    `
})
export class AppComponent { 
    public people = <IPerson[]>[
        {id: 1, name: "Mike"},
        {id: 2, name: "Jacob"},
        {id: 3, name: "Ralph"},
        {id: 4, name: "name4"},
        {id: 5, name: "name5"},
        {id: 6, name: "name6"},
        {id: 7, name: "name7"},
    ];
    public selectedPeople[];

    constructor(){
        this.selectedPeople = Array(6).fill(<IPerson>{ });
    }

    selectChanged(index, value){
        let person = this.people.find((person: IPerson) => person.id == value);

        this.selectedPeople[index] = person;
    }
}

export interface IPerson{
    id: number,
    name: string
}

编辑:

this.selectedPeople[index] = person;行会导致此问题。

2 个答案:

答案 0 :(得分:0)

更改您的HTML,如下所示,并检查:

<select *ngFor="let selectedPerson of selectedPeople;let i = index;" (change)="selectChanged(i, $event.target.value)">
  <option></option>
  <option *ngFor="let person of people" [attr.selected]="selectedPerson === person.id" [value]="person.id">{{ person.name }}</option>
</select>

答案 1 :(得分:0)

在选择上使用*ngFor显然会导致奇怪的问题。您应该将select包裹在div内。

<div *ngFor="let selectedPerson of selectedPeople; let i = index;">
    <select (change)="selectChanged(i, $event.target.value)" [value]="selectedPerson.id">
       <option></option>
       <option *ngFor="let person of people" [value]="person.id">{{ person.name }}</option>
    </select>
</div>
<pre>{{ people | json }}</pre>

我不确定这是否可以被视为angular2或它的错误,因为使用*表达式时会进行模板化。