简体   繁体   中英

Add link inside each row - ngx-datatable

I am veryyy new to angular. I'm trying to add a link on each row of ngx-datatable, when clicking on the first column of each row. This should take me to another page based on the row id, for example if I have a table for courses, the first column is the name of the course. When I click on the course name for each row I want to save the entire row id and call a function with this id, which should take me to the appropiate page for each course. The name of the course should be a visible link (clickable), with cursor: pointer on it. I would appreciate any idea that will help me make this work.

This is what I've tried so far (the link does not work):

 viewCourseTrainings(id: number){
    this.router.navigate(['/home-page/mentor-trainings/'+ id])
  }
 <ngx-datatable
      class="material"
      [rows]="rows"
      [columns]="columns"      
      [columnMode]="'force'"
      [headerHeight]="50"
      [footerHeight]="50"
      [rowHeight]="'auto'"
      [limit]="5">

<ngx-datatable-column name="Name" prop="name">
      <ng-template let-row="row" let-value="value">
            <a (click)="viewCourseTrainings(value.id)">{{value.name}}</a>
      </ng-template>
</ngx-datatable-column>

</ngx-datatable>

So far your code looks good, i would recommend you to pass the entire value and access the id in the TS

 <ngx-datatable-column prop="$key">
                <ng-template let-row="row" let-value="value" ngx-datatable-cell-template>
                  <a  class="nav-link edit" (click)="viewCourseTrainings(value)">
                    <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                  </a>
                </ng-template>
  </ngx-datatable-column> 

Curresponding TS

 viewCourseTrainings(valObj: any){
    this.router.navigate(['/home-page/mentor-trainings/'+ valObj.id])
  }

Thank you for your help, I managed to solve this problem.

<ngx-datatable-column name="Name" prop="name">
        <ng-template ngx-datatable-cell-template let-row="row" let-value="value">
          <a class="nav-link" (click)="viewCourseTrainings(row)">
            {{row.name}} <!-- or {{value}} -->
          </a>
        </ng-template>
</ngx-datatable-column>

And the TS is exactly as you said.

Actually there is a simpler way to do this. You can use routerLink and pass the row id using double curly brackets. This way there is no need to define anything in ts file. See my example:

<ngx-datatable-column name="Actions" [width]="80">
   <ng-template let-row="row" ngx-datatable-cell-template>
      <a routerLink="/mentor-trainings/{{row.id}}">View training</a>
   </ng-template>
</ngx-datatable-column>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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