简体   繁体   中英

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.

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.

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: ''}}">

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