簡體   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