首页 > 解决方案 > HTML 表格在表格列中正确使用和设置 mat-select

问题描述

我有这张桌子:

<table class="mat-elevation-z8">
              <tr>
                  <th align="left" mat-header="nomeFile"> Nome file </th>
                  <th align="left" mat-header="note"> Note </th>
                  <th align="left" mat-header="tipoDocumento"> Tipo documento </th>
                  <th></th>
                </tr>
            <tr *ngFor="let documento of documenti" class="mat-row">
                <td> {{documento.nome}} </td>
                <td> {{documento.note}} </td>
                <td> <mat-form-field class="col">
                    <mat-select formControlName="tipoDocumento" [(value)]="tipoDocumentoSelezionato">
                      <mat-option value="generico">Allegato Generico</mat-option>
                      <mat-option value="verbale">Verbale</mat-option>
                      <mat-option value="esito">Esito Analisi</mat-option>
                    </mat-select>
                  </mat-form-field> </td>
            </tr>
        </table>

这个实现的问题是,每当我在表的一行中选择一个选项时,表中的所有其他行都会为其 mat-select 设置相同的值。如果我为第一行选择选项“Esito Analisi”,这是输出:

在此处输入图像描述

我该如何解决这种行为?之后,如果我想保存数据,如何获取每一行的已选择选项的值?

标签: htmlhtml-tableangular7

解决方案


好的,解决方案非常愚蠢,但我希望它会对某人有所帮助。我设置[(value)]="documento.tipo"而不是将其绑定到“通用”变量。所以最后我有:

<tr *ngFor="let documento of documenti" class="mat-row">
                <td> {{documento.nome}} </td>
                <td> {{documento.note}} </td>
                <td> <mat-form-field class="col">
                    <mat-select [(value)]="documento.tipo">
                      <mat-option value="generico">Allegato Generico</mat-option>
                      <mat-option value="verbale">Verbale</mat-option>
                      <mat-option value="esito">Esito Analisi</mat-option>
                    </mat-select>
                  </mat-form-field> </td>
                <td>
                    <button mat-button class="delete" (click)="rimuoviDaDocumenti(documento)">delete</button>
                </td>
            </tr>

并在方法“rimuoviDaDocumenti(documento)”中获取所选选项:

  rimuoviDaDocumenti(documento){
    console.log("Documento " + documento.tipo);
  }

其中 documenti 是这个数组:

documenti = [
    {
    nome: "Doc 1",
    note: "notes",
    tipo: ""
  },
  {
    nome: "Doc 2",
    note: "notes",
    tipo: ""
  }

推荐阅读