Home > OS >  Angular 12 - *ngIf;Then;Else - must be a TemplateRef, but received '[object HTMLInputElement]&#
Angular 12 - *ngIf;Then;Else - must be a TemplateRef, but received '[object HTMLInputElement]&#

Time:09-01

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

I've my code like this

<table>
  <thead></thead>
  <tr>
    <th>
      <span *ngIf="myFunctionName(); then removeAll ; else selectAll"></span>
      <ng-template #selectAll>{{someThenableContentGoesHere}}</ng-template>
      <ng-template #removeAll>{{someEslePartWillComeHere}}</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>
      <ng-container *ngIf="myFunctionName(); then removeAll ; else selectAll"></ng-container>
      <ng-template #selectAll>{{someThenableContentGoesHere}}</ng-template>
      <ng-template #removeAll>{{someEslePartWillComeHere}}</ng-template>
    </th>
  </tr>
</table>

ts

myFunctionName(): boolean {
  if (this.checkboxes) {
    // other stufs
  }
  return false;
}

Could someone help me how to can refactor pieces ?

Thanks for the help guys

CodePudding user response:

This should fix your error:

<table>
  <thead></thead>
    <tr>
      <th>
        <ng-container *ngIf="myFunctionName(); else selectAll">
          {{someEslePartWillComeHere}}
        </ng-container>
        <ng-template #selectAll>{{someThenableContentGoesHere}}</ng-template>
      </th>
    </tr>
</table>

The ngIf directive should wrapper the content that you want to show when condition is true.

CodePudding user response:

Your code is fine, except the template reference variable used in ng-template. For example: there should not be any properties in your class as in the same name as #selectAll and #removeAll references

<ng-template #selectAll>{{someThenableContentGoesHere}}</ng-template>
<ng-template #removeAll>{{someEslePartWillComeHere}}</ng-template>
  • Related