繁体   English   中英

将 Angular Material Table 中的行数据显示到另一个组件中

[英]Displaying row data from Angular Material Table into another component

我有两个组件。 第一个组件包含 Angular Material Table,而第二个组件将显示在表格中单击的行的详细信息。

第一个组件:

    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);
    }

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

这是使用服务的示例(该示例是关于用户管理的):

  • 在您的 UserService 中,声明一个类型为 Subject 的属性 user。
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$ observable 以更新视图。
this.userService.user$.subscribe((userData) => {this.user = userData;});
  • 在您看来,只需使用字符串插值:
{{user?.firstName}} {{user?.lastName}}

这是工作plunker: http ://plnkr.co/edit/qUR0spZL9hgZkBe8PHw4?p=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM