将行数据从Angular Material表显示到另一个组件中

问题描述 投票:0回答:1

我有两个组成部分。第一个组件包含“角材料表”,而第二个组件将显示在表中单击的行的详细信息。

第一部分:

    const ELEMENT_DATA: GoodsList[] = [
    {initial: 'J', eta: '20-01-2020', src: 'IN'},
    {initial: 'N', eta: '20-01-2020', src: 'ON''}
]
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="ordered">
        <th mat-header-cell *matHeaderCellDef> Initial </th>
        <td mat-cell *matCellDef="let element"> {{element.initial}} </td>
    </ng-container>

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

    <ng-container matColumnDef="srt">
        <th mat-header-cell *matHeaderCellDef> SRC </th>
        <td mat-cell *matCellDef="let element"> {{element.src}} </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="getRecord(row)"></tr>
</table>

现在函数getRecord()可以正常工作。

    getRecord(row: GoodsList){
    console.log(row);
    }

数据是在行变量中捕获的,但是现在如何根据单击的内容将其传递到另一个组件中?

angular datatable angular-material angular-components
1个回答
0
投票

这里是使用服务的示例(该示例与用户管理有关:

  • 在您的UserService中,声明类型为Subject的属性用户。
user: Subject<User> = new Subject();
  • 以可观察的方式暴露在外面:
user$: Observable<User>
...
this.user$ = this.user.asObservable();
  • 登录功能将更新私人用户的主题。
login(userName: string, password: string) {
  //...
  this.user.next(new User("First name", "Last name"));
}
  • 在您的UserComponent中,可观察地订阅UserServive的user $以更新视图。
this.userService.user$.subscribe((userData) => {this.user = userData;});
  • 在您看来,只需使用字符串插值:
{{user?.firstName}} {{user?.lastName}}

这里是工作中的打孔器:http://plnkr.co/edit/qUR0spZL9hgZkBe8PHw4?p=preview

© www.soinside.com 2019 - 2024. All rights reserved.