Как получить идентификатор строки и входное значение из таблицы mat (angular) - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть таблица с несколькими столбцами, и один из них является входным. Под таблицей у меня есть кнопка, по нажатию которой я хотел бы обновить базу данных одним щелчком мыши, чтобы обновить возраст всех пользователей. Поэтому для вызова мне понадобится идентификатор строки и входное значение для каждого пользователя. Может кто-нибудь объяснить, как это сделать? Спасибо

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>

1 Ответ

0 голосов
/ 11 апреля 2019

Все, что вам нужно сделать, это связать значение вашего элемента input с помощью ngModel, и ваш dataSource будет обновлен.

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

См это , при нажатии кнопки сохранения обновленная модель будет введена в консоль.

...