【问题标题】:*ngIf or [hidden] not working correctly*ngIf 或 [hidden] 无法正常工作
【发布时间】:2018-08-09 14:05:48
【问题描述】:

我正在尝试通过用户切换来隐藏我正在处理的项目的某些部分。它保存在数据库中,并在使用以下代码在构造函数中加载页面时被拉取

this.http.get(`api/section/get/${this.id}`, this.id).subscribe(res => {
            this.section = res.json()[0];
            this.sect = res.json();
            console.log(this.section);

            this.hideIntro = this.sect[0].hideIntro;
            this.hideMainVideo = this.sect[0].hideMainVideo;
            this.hideHandout = this.sect[0].hideHandout;
            this.hideQuiz = this.sect[0].hideQuiz;

            console.log("Hide Intro = " + this.hideIntro);
            console.log("Hide Main = " + this.hideMainVideo);
            console.log("Hide Handout = " + this.hideHandout);
            console.log("Hide Quiz = " + this.hideQuiz);
});

HTML如下...

<div class="row classMainBackground col-md-12" *ngIf="!hideIntro">
...content...
</div>

出于某种原因,无论我做什么,无论我将其更改为 *ngIf="hideIntro == false" 还是使用 [hidden]="hideIntro",都无法正常工作。

即使是 .ts 文件中的控制台日志也能正确显示。这对我不起作用有什么原因吗?我已经在其他位置使用过它,它在那里工作得很好......

它与在构造函数中分配它有什么关系吗?

提前致谢!

【问题讨论】:

  • 我在这里猜测,但是 this.sect[0].hideIntro 是一个字符串吗?如果是,您可以尝试 *ngIf="hideIntro === 'false'"。注意 "" 里面的 ''。
  • 为了调试,可以在视图中显示hideIntro的值:&lt;div&gt;hideIntro: {{hideIntro}} &lt;/div&gt;
  • 嗯,hideIntro 是数据库中的一个布尔值(位),它被定义为一个 hideIntro: boolean; hideHandout:布尔值; hideMainVideo:布尔值; hideQuiz:布尔值;在 ts 文件中。我已经有了 hideIntro 的值,这就是控制台日志的作用。这样做对我来说更容易,因为...内容...实际上是我所有的内容。我之前也检查过它是否是一个字符串,但它不起作用。
  • 不确定您所说的“...内容...是我的全部内容”是什么意思。您是否尝试在 div 中显示{{hideIntro}}?如果是这样,你看到了什么?它可能与console.log 输出不同;这就是我推荐它的原因。
  • 它显示了一些不同的东西,你是对的。它正在显示 [object object]。现在只是想弄清楚为什么会发生这种情况,我假设有人在下面说了什么。

标签: html angular angular-ng-if


【解决方案1】:

角度变化检测运行以响应使用与组件的交互。如果值在该事件处理之外更新(例如在 HTTP 请求之后),您需要手动告知组件它已更改。

constructor(private changeDetector: ChangeDetectorRef){}

this.http.get(`api/section/get/${this.id}`, this.id).subscribe(res => {
    [...]
    this.changeDetector.markForCheck();
})

更多深度阅读:https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

【讨论】:

  • 老实说,我什至不担心它在这个时间点发生变化。我所担心的只是隐藏内容,如果该值是真的。从您的回复看来,这是为了在页面加载后更新某些内容。我只是想在页面加载时从数据库中获取数据,并使用 ngIf 根据布尔值显示/隐藏该内容,而不用担心之后能够更改它。
  • @AlexLiosatos 是的,这就是您需要使用它的情况。这本质上是一个时间问题。很容易认为代码运行loading starts -> http start -> http end -> page loaded,但这是不正确的。因为 http 请求是一个异步操作,所以浏览器会以不同的方式调度它。代码执行实际上是loading starts -> http start -> page loaded -> http end,所以你需要手动告诉Angular“嘿,有什么改变了”
【解决方案2】:

我最终通过在 HTML 中使用 {{!section.hideIntro}} 解决了这个问题,而不是尝试定义一个新变量来传递该布尔值。

我相信答案是 @Vlad274 和 @ConnorsFan 提到的组合。

HTML 正在为 {{hideIntro}} 返回一个 [object object],并且在 DOM 实际加载之前从 GET 响应分配新值数据之间似乎存在延迟。

直接从 GET 响应变量中获取数据最终成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2014-10-10
    • 2020-08-15
    相关资源
    最近更新 更多