【问题标题】:Pass data row from mat-table when click to another component in Angular 7单击到Angular 7中的另一个组件时从mat-table传递数据行
【发布时间】:2019-11-15 09:41:55
【问题描述】:

我想将整行传递给其他组件以显示此数据,任何机构都有办法做到这一点。

HTML:

    <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="getRecord(row)"></mat-row>

ts:

  //Get row data when the click
  getRecord(row){
      // Do somthing ..... //
  }

我会搜索很多,我找不到路。

【问题讨论】:

  • row 变量应该有行数据,尝试打印到控制台console.log(row);
  • 您已经从mat-table 将数据传递给getRecord() 函数,所以我认为您的问题主要是关于如何将数据传递给其他组件。你的组件之间是什么关系?
  • 是的,我想将行传递给其他组件,关系是兄弟。
  • 数据是strings和int和image

标签: angular angular-material angular7 angular8 angular7-router


【解决方案1】:

单击该行后,我通过以下步骤解决了我的问题:

  1. 将数据保存在服务文件的变量中。
  2. 使用导航进行路由。
  3. 从服务文件中的变量中获取数据。
   public  getRecord(row : any){
    console.log(row);
     this.userservice.dataRow = row;
     this.router.navigate(['/profile']);
  }

服务文件:

    //Temporarily stores row data from mat-table
    dataRow:any;

profile.ts:

    this.dataRow = this.userservice.dataRow;

【讨论】:

    【解决方案2】:

    可能有不止一种方法可以完成兄弟之间的数据传递,但 Angular 的方法是使用服务:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

    您还可以通过事件传递数据。让行点击触发父组件接收的事件,然后通过函数传递给子表的兄弟。

    【讨论】:

    • 感谢您的回答,但此链接适用于有孩子的父母
    • 是的,我知道 - 这就是我的回答 - 我看到你已经按照我的建议通过服务解决了这个问题。
    • 非常感谢(:我会提高你的费率
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多