带有下拉列表的动态生成的行中的数据绑定

时间:2018-09-07 18:29:25

标签: angular typescript angular-material angular-ngmodel

我有一个表,该表可以动态生成包含上载文件详细信息的行。这些行都有一个下拉列表来选择文件类型。

我目前面临着动态生成的下拉菜单的问题。如果我在任何一个下拉列表中选择一个值,它将为所有行中的所有下拉列表设置相同的值。

HTML:

<table>
 <thead>
  <tr>
   <th>File Name</th>
   <th>File Type</th>
  </tr>
 </thead>

 <tbody>
  <tr *ngFor="let item of uploader.queue">
   <td>
    {{ item?.file?.name }}
   </td>

   <td>
    <mat-form-field>
      <mat-select  placeholder="Select File Type" [(ngModel)]="selectedType">
        <mat-option *ngFor="let type of Types" [value]="type.type">
          {{type.type}}
        </mat-option>
       </mat-select>
     </mat-form-field>
   </td>
   <td>
    <button (click)="AddPdf(item)">Upload</button>
   </td>
  </tr>
 </tbody>
<table>

TS:

public AddPdf(Filenames: FileItem) {
  this.data = { filename: FileNames.file.name.toString() , LetterName:this.selectedLetterName, LetterType: this.selectedType };
  console.log(this.data.filename, 'File Name');
  console.log(this.data.LetterName, 'Letter Name');
  console.log(this.data.LetterType, 'Letter Type');
}

现在,如果我添加三个文件,则会生成三行。如果我为一行选择文件类型,则所有行都将反映相同的类型。

请帮助我在这里了解缺陷!

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我发现了问题。我没有将[(ngModel)]分成两部分,如下所示:

        <mat-form-field>
          <mat-select
            placeholder="Select Letter Name"
            #lettername
            [ngModel]="selectedLetterName"
            (ngModelChange)="onLetterNameSelect($event)"
            [ngModelOptions]="{standalone: true}">
            <mat-option *ngFor="let LetterName of LetterNames" [value]="LetterName.ReportName">
              {{LetterName.ReportName}}
            </mat-option>
          </mat-select>
        </mat-form-field>

更改后,它按预期工作。