【问题标题】:Get row id and input value from mat-table (angular)从 mat-table 获取行 id 和输入值(角度)
【发布时间】:2019-04-11 13:54:28
【问题描述】:

我有一个包含几列的表,其中之一是输入。在表格下我有一个按钮,点击它我想更新数据库,一键更新所有用户的年龄。因此,对于通话,我需要每个用户的行 ID 和输入值。谁能解释一下怎么做?

TS

const ELEMENT_DATA: User[] = [
  { id: 1, country: 'UK', name: 'A', age: 20 },
  { id: 2, country: 'France', name: 'B', age: 21 },
  { id: 3, country: 'Germany', name: 'C', age: 22 }
];

export interface User {
    id: number;
    country: string;
    name: string;
    age: number;
}

@Component({
  selector: 'app-table',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})
export class TableComponent implements OnInit {

  displayedColumns = ['country', 'name', 'age'];
  dataSource = ELEMENT_DATA;

  ngOnInit() {
  }
}

HTML

<div>
  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <ng-container matColumnDef="country">
      <th mat-header-cell *matHeaderCellDef> Country </th>
      <td mat-cell *matCellDef="let element"> {{element.country}} </td>
    </ng-container>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <ng-container matColumnDef="age">
      <th mat-header-cell *matHeaderCellDef> Age </th>
      <td mat-cell *matCellDef="let element">
        <div>
          <input type="text" class="age-input" value="{{element.age}}">
        </div>
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table> 

  <button mat-raised-button type="submit">
    <i class="material-icons mr-2">save</i>Save
  </button>

</div>

【问题讨论】:

    标签: angular input angular-material mat-table


    【解决方案1】:

    您只需通过ngModel 绑定input 元素的值,您的dataSource 就会更新。

    <input type="text" class="age-input" [(ngModel)]="element.age">
    

    this, 单击保存按钮后,更新的模型将打印到 控制台。

    【讨论】:

    • 谢谢,我现在可以获取数据,但是如何仅获取 Id 和 Age(以便我可以将这些值传递给后端)。我尝试使用 .map 但没有成功...
    猜你喜欢
    • 2014-12-12
    • 2021-12-06
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多