角垫输入将[value]绑定到[(ngModel)]

时间:2019-07-05 09:00:56

标签: angular binding angular7 mat-input

我有这张桌子:

<table class="mat-elevation-z8">
          <tr *ngFor="let prescription of prescriptions" class="mat-row">
            <td>
              <mat-form-field class="">
                <input  [value]="prescription.description" matInput placeholder="Description">
              </mat-form-field>
            </td>
            <td>
              <mat-form-field class="">
                  <mat-select>
            <mat-option *ngFor="let object of selectedObjects" [value]="object.id" [(ngModel)]="prescription.idObject">
              {{object.description}}
            </mat-option>
          </mat-select>
        </mat-form-field>   
            </td>
            <td>
              <button mat-button class="delete" (click)="check(prescription)">delete</button>
            </td>
          </tr>
        </table>

我的处方药具有以下结构:

 prescriptions = [
    {
      id: 1,
      description: "Prescrizione 1",
      date1: new Date(),
      date2: new Date(),
      idObject: 0
    },
    {
      id: 2,
      description: "Prescrizione 2",
      date1: new Date(),
      date2: new Date(),
      idObject: 0
    }
  ]

表的每一行代表此数组的一个对象。每行中都有一个mat-select元素,该元素从此selectedObjects数组中进行选择:

"selectedObjects": [
        {
            "id":1, "description": "Desc1"
          },
          {
            "id":2, "description": "Desc2"
          },
          {
            "id":3, "descrizione": "Desc3"
          }

我要实现的是将所选选项的值object.id绑定到row元素的属性idObject。所以我所做的是使用[value]="object.id" [(ngModel)]="prescription.idObject",但是它不起作用,因为该属性对于所有行都保持为0。我已经通过在方法check中打印属性(对于每一行)进行了检查。
有没有办法实现这种绑定?

1 个答案:

答案 0 :(得分:1)

您需要将ngModel放置在select而不是选项上。您选择的是“更改”,并且每次选择选项而不是选项本身都会被设置。看这个例子: https://stackblitz.com/angular/vkkalkxbmrok?file=app%2Fselect-form-example.ts

编辑:好的,我明白了您要在这里做什么。您想在每个处方中设置idObject。将ngModel绑定到select上,将复制selectedObjects中的整个选定对象,而不仅仅是ID:

{"id":2, "description": "Desc2"}

我不确定您是否可以指定我只想要该选择的子对象,但这是可以使用的理想情况:

(selectionChange)="setPrescriptionId($event, prescription)"

Angular 6 Material mat-select change method removed

每次您的选择更改时,都会调用它。

public setPrescriptionId(event: {id:string, description: string}, prescription: IYourPrescriptionInterface) {
    prescription.idObject = event.id;
}
相关问题