在Angular 6中,您可以使用Angular Material的Table组件来获取选定行的值。以下是一个示例解决方法:
npm install --save @angular/material @angular/cdk @angular/animations
import {MatTableModule} from '@angular/material/table';
import {MatButtonModule} from '@angular/material/button';
@NgModule({
imports: [
MatTableModule,
MatButtonModule
],
...
})
export class AppModule { }
Name
{{element.name}}
Age
{{element.age}}
import { Component } from '@angular/core';
export interface UserData {
name: string;
age: number;
}
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.css']
})
export class TableComponent {
displayedColumns: string[] = ['name', 'age'];
dataSource: UserData[] = [
{name: 'John Doe', age: 30},
{name: 'Jane Smith', age: 25},
{name: 'Bob Johnson', age: 40}
];
selectedRow: UserData;
getSelectedRow() {
this.selectedRow = this.dataSource.find(row => row === this.selection.selected[0]);
console.log(this.selectedRow);
}
}
在上面的代码中,我们定义了一个名为UserData
的接口来表示表格中的数据对象。displayedColumns
数组定义了要显示的列,dataSource
数组包含表格的数据。selectedRow
变量用于存储选定行的值。
getSelectedRow()
方法使用find()
方法从数据源中查找选定的行,然后将其赋值给selectedRow
变量,并在控制台中打印出来。
这就是获取选定行的值的解决方法。您可以根据自己的需求进行修改和扩展。