【问题标题】:View not updating when tap function changes variable used in ngIf condition当点击函数更改 ngIf 条件中使用的变量时,视图不更新
【发布时间】:2016-12-17 13:51:27
【问题描述】:

我试图根据用户点击的按钮显示模板的不同部分。

我不确定这是否是我需要通知 Angular 应该运行更改检测的情况? (我是 Angular 2 的新手,所以试图掌握这个概念)

模板:

    <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>

组件:

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

行为:

  • 正确的选项卡 (0) 在初始加载时显示,当我单击“显示选项卡 1”时会消失,但选项卡 1 不会显示。
  • 再点击“显示选项卡 0”没有任何作用。

感谢您的帮助!

【问题讨论】:

  • 你有没有通过应用console.log(this.currentTab)检查currentTab的值;在你的showTab ??你有什么错误吗?
  • Amit- 是的,我可以通过控制台记录 this.currentTab 的值并且设置正确。控制台中没有错误。
  • 我测试了您的代码,在 iOS 模拟器上没有任何问题。我会检查您使用的版本,因为它们可能已过时。另外您使用的是哪个平台,这是在真实设备还是模拟器上?

标签: angular typescript nativescript angular2-nativescript


【解决方案1】:

您的代码对我来说似乎是正确的。但你可以尝试制作你的 currentTab: boolean=false;

代码为

    <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>

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

也试试这种方式 showTab(num: number){ } 代替 showTab = (num: number) => {} ;并检查您的类型。

【讨论】:

  • 我试过这个,结果一样。我可以在控制台中正确看到布尔值,但视图没有更新。在 NativeScript 布局标签上使用 ngIf 会不会有什么问题?
  • 这通常以角度工作。我每天都用这些东西。我还没有尝试过 NativeScript。但如果它与更改检测有关,那么您应该尝试 ngZone。有时当我使用流星和角度 2 的集成时,我会遇到这类问题。试试 ngZone。检查我的这个答案stackoverflow.com/questions/41145290/…希望这会对你有所帮助。
【解决方案2】:

您是否尝试使用 [hidden] 而不是 *ngIf

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2018-11-25
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 2019-04-27
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多