首页 > 解决方案 > 使用打字稿更改动态选择的值

问题描述

嗨,我有这段代码:

<div>
    <div *ngIf="!showInfo">
      <div >
          <br>    
<table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;">
                <tbody>
                  <tr>
                    <th style="color: black;border: 0px;">Type</th>
                    <th style="color: black;border: 0px;">Radius</th>
                    <th style="color: black;border: 0px;">Number</th>
                  </tr>
                  <br>
                  <tr *ngFor="let row of groups;let i = index">
                    <td style=" border: 0px;" >
                      <input #focus matInput type='text' style=" border: 0px;"  type="text" value="{{row.type}}" readonly  [(ngModel)]="row.type" >
                    </td>
                    <td>
                      <select (change)="changeRadius($event, i)" attr.id="{{row.id}}" [value]="5000">
                        <option *ngFor="let meters of radius"  [value]="meters.value">{{meters.value}}</option>
                      </select>
                    </td>
                    <td style="margin-left: 60px; border: 0px;">
                      <input  matInput type='text' style="margin-left: 30px; border: 0px;" readonly  type="text" value="{{row.number}}" [(ngModel)]="row.number">
                    </td>
                  </tr>
                </tbody>
              </table>
            <hr style="color: darkred;" >

            <div>
              <button mat-button class="custom-button" (click)="getNewRadius()">
                  OK
              </button> 

第一次出现此表时,我希望每个选择都像选择的选项 5000,因此用户为每个选择选择新的半径并单击“确定”。在我的打字稿中,我有一个数组“radiousToSend”,其中包含每个选择的选定radious。现在我希望每次出现此表时都像选定的选项一样,用户上次选择的值是“radiousToSend”中的值

我试图做这样的事情:

let pan = (<HTMLInputElement>document.getElementById('1'));
    pan[0].options[pan[0].options.selectedIndex].selected = true;

但它不起作用,因为每次出现此表时,每个选择都具有选定值 = 5000,但我希望只有第一次该值是静态的。

标签: angulartypescriptselect

解决方案


您可以使用带有指令的双向绑定ngModel来绑定到控制器中的变量。

模板

<select (change)="changeRadius($event, i)" attr.id="{{row.id}}" [(ngModel)]="selectOption">
  <option *ngFor="let meters of radius" [value]="meters.value">{{meters.value}}</option>
</select>

selectOption在点击事件处理程序中设置变量的值。

控制器

export class AppComponent  {
  selectOption = 5000;   // <-- default value of all select options

  getNewRadius() {    // <-- change all options to 1000 on button click
    this.selectOption = 1000;
  }
}

推荐阅读