Search code examples
angularangular-template

Angular template variable used to disable button throws compile error


I am trying to use Angular template variables to pass values to a button that calls the backend. When I compile the code below I get an error. Why is the angular template throwing an error? I used an example from the docs here: https://angular.io/guide/template-reference-variables

I assumed it might be because:

The structural directive, *ngFor instantiates the template twice because *ngFor iterates over the two items in the array. It is impossible to define what the ref.value reference signifies.

however I dont understand it.... wouldn't the selected option be the one that is instantiated? And if its not instantiated wouldn't it be undefined?

ERROR in src/app/statusview/statusview.component.html:84:96 - error TS2339: Property 'endo' does not exist on type 'StatusviewComponent'.

84                         <button mat-raised-button color="primary" (click)="ReloadOdataEndpoint(endo.value)"

Code

                <select>
                    <option *ngFor="let t of selectedCustomer.endpoints" #endo [ngValue]="t.name">
                        {{t.name}}
                    </option>
                </select>
                <button mat-raised-button color="primary" (click)="ReloadEndpoint(endo.value)"
                    disabled="!endo" style="margin: 5px;">
                    Load Endpoint
                </button>

Note: None of these vars are declared in the template- im trying to set them in html and pass them in the template


Solution

  • You cannot reference an option element, you will have one reference for multiple elements. Put it on the select and pick the value.

    <select #endo>
      <option *ngFor="let t of selectedCustomer.endpoints" [ngValue]="t.name">
       {{t.name}}
      </option>
    </select>
    <button mat-raised-button color="primary" (click)="ReloadEndpoint(endo.value)" disabled="!endo" style="margin: 5px;">
     Load Endpoint
    </button>