Skip to content
Advertisement

Angular 12 – *ngIf;Then;Else – must be a TemplateRef, but received ‘[object HTMLInputElement]’

After migrating Angular 6.x to Angular 12.x, I’m facing template related issues.

UPDATED

I’ve my code like this

    <table>
  <thead></thead>
  <tr>
    <th>
      <input #selectAll type="checkbox" [checked]="myFunctionName()" (click)="toggleSelection()"
      />
    </th>
    <th>
      <span *ngIf="myFunctionName(); then removeAll ; else selectAll"></span>
      <ng-template #selectAll>{{SELECT_ALL}}</ng-template>
      <ng-template #removeAll>{{DESELECT_ALL}}</ng-template>
    </th>
  </tr>
</table>

Below error i got

ERROR Error: ngIfElse must be a TemplateRef, but received ‘[object HTMLInputElement]’

What i tried?

<table>
      <thead></thead>
      <tr>
        <th>
          <input #selectAll type="checkbox" [checked]="myFunctionName()" (click)="toggleSelection()"
          />
        </th>
        <th>
          <ng-container *ngIf="myFunctionName(); then removeAll ; else selectAll"></ng-container>
          <ng-template #selectAll>{{SELECT_ALL}}</ng-template>
          <ng-template #removeAll>{{DESELECT_ALL}}</ng-template>
        </th>
      </tr>
    </table>

ts

@ViewChild('selectAll' , {static: true}) selectAll!: ElementRef<HTMLInputElement>;
    myFunctionName(): boolean {
      if (this.checkboxes) {
        // other stufs
      }
      return false;
    }

Could someone help me how to can refactor pieces ?

Thanks for the help guys

Advertisement

Answer

so the problem is very simple, you have #selectAll twice in your HTML code. to fix this you need to rename one of them

<ng-container *ngIf="myFunctionName(); then removeAllBlock; else selectAllBlock"></ng-container>
<ng-template #selectAllBlock>{{SELECT_ALL}}</ng-template>
<ng-template #removeAllBlock>{{DESELECT_ALL}}</ng-template>

and if you use the selectAll input only in your function, you don’t need the @ViewChild but you can do it like this: (just an improvement, not mandatory)

 <input #myInput type="checkbox" [checked]="myFunctionName()" (click)="toggleSelection(myInput)"/>
toggleSelection(myInput:HTMLInputElement){
// do stuff with your input
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement