Search code examples
angular9angular-ng-ifionic5ng-template

*ngIf doesn't work with ng-template (ionic 5/angular 9)


Here is my component.page.ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-domestic',
  templateUrl: './domestic.page.html',
  styleUrls: ['./domestic.page.scss'],
})
export class DomesticPage implements OnInit {
  opchoice: string;

  constructor() { }

  ngOnInit() {
    this.opchoice = "From";
    console.log("OnInit opchoice? " + this.opchoice);
  }
  onFromToChange (ev: any) {
    console.log("OnFromToChange");
    this.opchoice = ev.detail.value;
    console.log("opchoice? >" + this.opchoice + "<");
  }
}

and the HTML file.

<ion-content>
  <ion-segment value="From" (ionChange)="onFromToChange($event)">
    <ion-segment-button value="From">Pickup From</ion-segment-button>
    <ion-segment-button value="To">Deliver To</ion-segment-button>
  </ion-segment>
  <div *ngIf="opchoice=='From'; then ShowFrom else ShowTo">
    <ng-template #ShowFrom class="ion-text-wrap ion-no-padding ion-no-margin">
            <ion-item>Domestic - Ship From</ion-item>
    </ng-template>
    <ng-template #ShowTo class="ion-text-wrap ion-no-padding ion-no-margin">
      <ion-item>Domestic - Ship To</ion-item>
    </ng-template>
  </div>
</ion-content>

However, the page doesn't display anything (it is empty) whether I click on the "Pickup From" or "Deliver To" Tabs/buttons.

Is there something I am doing wrong or have not understood about ng-template or ngIf? As you can see, I am printing the value of the opchoice variable and it prints correctly for each type of click. I have tried putting the ngIf in the ion-item, in an ion-grid and many other combinations, but none work.

I am using Ionic 5 with Angular 9. Any help is appreciated.


Solution

  • As I said before, you have to put the ng-templates at the same level. For me the cleanest solution is:

    <div class="ion-text-wrap ion-no-padding ion-no-margin">
      <div *ngIf="opchoice=='From'; else ShowTo">
        <ion-item>Domestic - Ship From</ion-item>
      </div>
      <ng-template #ShowTo>
        <ion-item>Domestic - Ship To</ion-item>c
      </ng-template>
    </div>