angular - 从 mat-table 获取行 id 和输入值( Angular )

标签 angular input angular-material mat-table

我有一个包含几列的表,其中一列是输入。在表格下,我有一个按钮,单击该按钮我想更新数据库,一键更新所有用户的年龄。因此,对于调用,我需要每个用户的行 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>

最佳答案

您需要做的就是通过 ngModel 绑定(bind) input 元素的值,您的 dataSource 将被更新。

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

See this, on click of the save button the updated model will be printeg to the console.

关于angular - 从 mat-table 获取行 id 和输入值( Angular ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55634209/

相关文章:

css - Sass 错误 : Invalid CSS after "typography-config" angular 4. x

JavaScript 更改输入类型 ="date"格式和值

md-toolbar 的 CSS 媒体查询

悬停时 Angular Material 按钮发生变化

java - 扫描仪类输入问题

javascript - 内联 SVG 无法在 Angular Material 对话框中正确缩放

css - Angular : add a fixed search barch to a mat-select dropdown

angular - try catch 错误处理不会捕获错误

html - Angular 2+ 如何在运行时获取 div 的像素宽度

JavaScript 函数难度