ngIf的值不会随着变量的改变而改变



这个问题已经被问过很多次了,但是没有一个解决方案适合我,我花了几个小时试图找出为什么它不起作用,但我仍然没有答案。所以,我使用lottie json动画,一旦动画停止/完成,我想在屏幕上显示文本。所以我在函数调用中改变了一个标志但是当我试图检查页面时,它总是显示

<--bindings={
"ng-reflect-ng-if":"false"
}-->

我认为这意味着标志值没有得到更新。HTML代码

<html>
<img class="bg-img" src="assets/black.jpg" alt=""> 
<p *ngIf="displayText" style="color: white; position: relative;">Hello</p>
<div style="position: fixed; top: 0; left: 0; width:100vw; height:100vh">
<ng-lottie width="100%" height="100%" [options]="options" (complete)="onComplete()"></ng-lottie>
</div>
</html>

和我的组件。ts代码

import { Component } from '@angular/core';
import { AnimationOptions, BMCompleteEvent } from "ngx-lottie";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
options: AnimationOptions = {
path: "/assets/2version.mp4.lottie.json",
loop: false,
autoplay: true,
};
displayText = false;
onComplete(){
this.displayText=true
console.log(this.displayText)
}
}

控制台输出正确的值。任何帮助都将不胜感激。蒂娅!

在Angular中,有些情况下属性更新可能不会自动触发变更检测。需要手动触发变更检测的一个常见场景是,当你更新Angular区域之外的属性时。

为了手动触发变更检测,您可以使用changeDetectorRef

这样做
import { Component } from '@angular/core';
import { AnimationOptions, BMCompleteEvent } from "ngx-lottie";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
options: AnimationOptions = {
path: "/assets/2version.mp4.lottie.json",
loop: false,
autoplay: true,
};
displayText = false;

constructor(private cdr: ChangeDetectorRef) {}
onComplete(){
this.displayText=true
console.log(this.displayText)
this.cdr.detectChanges();
}
}

最新更新