Austin Ballard
Austin Ballard

Reputation: 143

A reference variable is being treated as both unused and undefined. Why?

I'm using references in my HTML code to pass the value of an input into a JavaScript function. However, while one reference variable (#options) works fine, the other (#current) is marked in one place as "unresolved/undefined" and in its declaration as "unused." I can't figure out what the difference is between them and why this is happening.

I know it's not an issue with duplicity of reference, because current works fine if it's placed in a (click) event in its own input element; however, it can't be an issue of scope either, because the inputs reference options just fine. So why can't the icon functions reference current in return?

<ng-container matColumnDef="maxInstalls">
        <th mat-header-cell *matHeaderCellDef>Max Installs</th>
        <td mat-cell *matCellDef="let profile">
          <input #current (click)="showDiv(options)" class="hiddenInput" type="number" min="0"
                 *ngIf="(profile.maximumInstalls > 0)" value="{{profile.maximumInstalls}}">
          <input #current (click)="showDiv(options)" class="hiddenInput" type="number" min="0"
                 *ngIf="(profile.maximumInstalls == 0)" value="">
          <div #options hidden="true">
            <mat-icon (click)="changeMaxInstalls(current, profile, options)">done</mat-icon>
            <mat-icon (click)="hideDiv(options)">clear</mat-icon>
          </div>
        </td>
      </ng-container>

I expect changeMaxInstalls() to pass the current variable into the function; however, it throws an error that current is undefined. Also, in my IDE, the declarations of the #current references are flagged as "unused local variables." showDiv() and hideDiv() reference options without issue.

Upvotes: 0

Views: 159

Answers (2)

Darren Ruane
Darren Ruane

Reputation: 2485

You are using the same Template Reference Variable for two elements (#current). These variables are intended to be unique across an entire template. The Angular docs say the following in the post I linked:

The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.

Upvotes: 1

Narshe
Narshe

Reputation: 466

I think it's because you have two elements with the #current tag.

You can achieve the same by using a single element with a ternary:

<input #current (click)="showDiv(options)" class="hiddenInput" type="number" min="0"  value="{{(profile.maximumInstalls > 0) ? profile.maximumInstalls: ''}}">

Upvotes: 0

Related Questions