Home > front end >  Is there a way to use variables which are declared in HTML in HTML lines before their declaration?
Is there a way to use variables which are declared in HTML in HTML lines before their declaration?

Time:09-07

I would like to use the rowData var which is declared in my second HTML line in line 1. For now I obviously get the "Property 'rowData' does not exist on type 'AppComponent'" error in line 1. rowData in the fourth line is working as expected. Is there a way to use a var which isn't declared yet? Something like a placeholder or something? I am using Angular (HTML and Typescript) with PrimeNG.

HTML:

...
<p-table selectionMode="single" (onRowSelect)="onRowSelect(rowData)>
<ng-template pTemplate="body" type="default" let-rowData let-columns="columns">
 <tr [pSelectableRow]="col">
  <td><icon (click)="openComponent(rowData)"></td>
...

CodePudding user response:

First option with $event :

<p-table selectionMode="single" (onRowSelect)="onRowSelect($event)">
<ng-template pTemplate="body" type="default" let-rowData let-columns="columns">
 <tr [pSelectableRow]="col">
  <td><icon (click)="openComponent(rowData)"></td>

Second option with [(selection)] :

<p-table selectionMode="single" [(selection)]="selectedRow" (onRowSelect)="onRowSelect()">
<ng-template pTemplate="body" type="default" let-rowData let-columns="columns">
 <tr [pSelectableRow]="col">
  <td><icon (click)="openComponent(rowData)"></td>

And in your function onRowSelect, you need to use variable this.selectedRow

CodePudding user response:

There is a kind of "placeholder" you can use it with an EventEmitter (import it from @angular/core) and it is called $event.

It is a slightly different construct, though. I will try to explain.

In your Component you declare an @Output and assign it an EventEmitter like this:

@Output() setActiveItem = new EventEmitter<any>();

And listen e.g. bind it to another function, wich will take the $event in your Template like this:

<your-component (setActiveItem)="someOtherFunction($event)"></your-component>

Now you can call the emitter like this (note that we call the emit-method on the emitter):

<li (click)=setActiveItem.emit(rowData)> whatever </li>

someOtherFunction will now receive the $event wich will carry your rowData or whatever you emit with it.

Hope this helps

Cheers Phil

  • Related