View not updating when tap function changes variable used in ngIf condition

789 views Asked by At

I am attempting to show a different portion of my template depending on which button a user taps on.

I'm not sure if this is a case where I need to inform Angular that Change Detection should run? (I'm new to Angular 2, so trying to grasp this concept)

Template:

    <Button (tap)="showTab(0)" text="Show Tab 0"></Button>
    <Button (tap)="showTab(1)" text="Show Tab 1"></Button>
    <StackLayout *ngIf="currentTab == 0">
        <Label text="Tab 0"></Label>
    </StackLayout>
    <StackLayout *ngIf="currentTab == 1">
        <Label text="Tab 1" class="user-name"></Label>
    </StackLayout>

Component:

export class MyComponent {
  currentTab: number = 0;
  ...
  showTab = (num: number) => {
    this.currentTab = num;
  }
  ...
}

Behavior:

  • The correct Tab (0) shows on initial load, and will disappear when I click on "Show Tab 1", but Tab 1 will not show.
  • Clicking back on "Show Tab 0" doesn't do anything.

Thanks for your help!

2

There are 2 answers

2
Amit kumar On

Your code seems correct to me. but can you try making your currentTab: boolean=false;

and code as

    <Button (tap)="showTab(false)" text="Show Tab 0"></Button>
    <Button (tap)="showTab(true)" text="Show Tab 1"></Button>
    <StackLayout *ngIf="!currentTab">
        <Label text="Tab 0"></Label>
    </StackLayout>
    <StackLayout *ngIf="currentTab">
        <Label text="Tab 1" class="user-name"></Label>
    </StackLayout>

and

export class MyComponent {
  currentTab: boolean = false;
  ...
  showTab(num: boolean){
    this.currentTab = num;
  }
  ...
}

also try this way showTab(num: number){ } in place of showTab = (num: number) => {} ; and check your types.

0
Mete Cantimur On

Did you try using [hidden] instead of *ngIf ?