Chetan Birajdar
Chetan Birajdar

Reputation: 471

How to get elements of selected row, and show it , using angular 2+ and typescript

I am using a table and I have to capture the data and show it separately when I click a particular row in a table, I was able to highlight the selected row, and capture the row no. and show it. I am not sure how can I capture the items in the selected row and show it.

The code I have done so far is,

HTML Markup:

<mat-tab label="PINS" flex>
    <div id="pinsDataSource" *ngFor="let pin of pins; let i = index" (click)="setClickedRow(i)" [class.alertactive]="i == selectedRow">

              {{pin.alertTitle}}  
              {{pin.alertCode}} 
              {{pin.date | date:'MM/dd/yyyy'}}

    </div>  
</mat-tab>

Here I want to show, the items that I have selected from that particular row like:

<div>
  Selected Row :
  <strong>{{selectedRow}}</strong>
</div>

component.ts file:

pins: any[];
selectedRow: Number;
setClickedRow: Function;

constructor(private proService: ProService) {
  this.setClickedRow = function (index) {
    this.selectedRow = index;
  }
}

ngOnInit() {
  // here the table items are called from webapi
  this.proService.getPinnedAlerts().subscribe(res => {
    this.pins = res;
  });
}
}

Upvotes: 1

Views: 5871

Answers (4)

Ashu Mhatugade
Ashu Mhatugade

Reputation: 80

Just pass an instance of your pins data in your function, which is you are calling on div as below:

     <mat-tab label="PINS" flex>
        <div id="pinsDataSource" *ngFor="let pin of pins; let i = index" (click)="setClickedRow(i, pin)" [class.alertactive]="i == selectedRow">

                  {{pin.alertTitle}}  
                  {{pin.alertCode}} 
                  {{pin.date | date:'MM/dd/yyyy'}}

          </div>  
      </mat-tab>

I have passed pin instance of pins data and capture it on your ts file.

    pins: any[];
    selectedRow: Number;
    setClickedRow: Function;

    constructor(private proService: ProService) {
    this.setClickedRow = function (index) {
      this.selectedRow = index;
    }
    }

    ngOnInit() {
    // here the table items are called from webapi
    this.proService.getPinnedAlerts().subscribe(res => {
      this.pins = res;
    });  

    }

    setClickedRow( index, rowData)
       console.log("row data", rowData);
    }

Upvotes: 2

Abhishek Jaiswal
Abhishek Jaiswal

Reputation: 253

You are using setClickedRow as function in markup, but it is defined as property in typescript file. Remove the code inside the constructor. Instead , do this

selectedRow: Number;
setClickedRow(i){
  this.selectedRow = i;
}
constructor(private proService: ProService) {
  this.setClickedRow(index);
}

Upvotes: 1

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

Pass the object as paramter to the function and assign the parameter to selectedRow

(click)="setClickedRow(pin )"

setClickedRow(pin ){

   this.selectedRow = pin
}

Upvotes: 2

Related Questions