在ngFor select选项中,如何在onChange

时间:2019-06-12 08:57:28

标签: angular

<select class="form-control" (change)="onChange(user.id)">
            <option disabled selected="selected">By User</option>
          <option *ngFor="let user of allUsers">{{user.first_name}} {{user.first_name}}</option>
        </select>

名字和姓氏仅用于显示我需要发送到ts文件的值为user.id

(change)="onChange(user.id)确实可以工作,因为它在循环之外。我需要在更改后发送所选用户ID的值。

4 个答案:

答案 0 :(得分:0)

您需要将user.id绑定到<option>标签的值:

<select class="form-control" (change)="onChange($event.target.value)">
  <option disabled selected="selected">Invoice By User</option>
  <option *ngFor="let user of allUsers" [value]="user.id">
    {{user.first_name}} {{user.first_name}}
  </option>
</select>

有关更多示例和信息,请参见here

答案 1 :(得分:0)

我认为应该是这样的

<select (change)="onChange($event.target.value)">
 <option *ngFor="let user of allUsers" [value]="user.id">{{user.first_name}} {{user.first_name}}
 </option>
</select>

答案 2 :(得分:0)

<select class="form-control" formControlName="userInvoice" (change)="onChange()">
  <option disabled selected="selected">Invoice By User</option>
  <option *ngFor="let user of allUsers" [value]="user.id">
    {{user.first_name}} {{user.first_name}}
  </option>
</select>

onChange(){
    console.log(this.userInvoiceformGroup.get('userInvoice').value);
}

答案 3 :(得分:-1)

尝试以下方法:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let user of allUsers">{{user.first_name}} {{user.first_name}}</option>
</select>

onChange这样

onChange(user) {
    console.log(user);
}