Angular中变量更新后ngIf值未变更问题求助
问题解决:ngx-lottie动画完成后*ngIf未触发视图更新
问题根源
ngx-lottie依赖的lottie-web库触发的complete事件可能运行在Angular变更检测上下文之外,导致Angular无法感知到displayText的状态变化,因此视图没有同步更新。另外你的文本元素存在被全屏动画div遮挡的问题,即使状态生效也无法显示。
解决方案1:手动触发变更检测
引入ChangeDetectorRef,在修改displayText后手动通知Angular执行变更检测:
import { Component, ChangeDetectorRef } from '@angular/core'; import { AnimationOptions } 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; this.cdr.detectChanges(); // 手动触发变更检测 console.log(this.displayText); } }
解决方案2:用NgZone包裹回调逻辑
将onComplete的逻辑包裹在Angular的Zone上下文内,确保事件触发在变更检测范围内:
import { Component, NgZone } from '@angular/core'; import { AnimationOptions } 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 zone: NgZone) {} onComplete(){ this.zone.run(() => { this.displayText = true; console.log(this.displayText); }); } }
额外修复:文本遮挡问题
动画div为全屏fixed定位,会覆盖文本元素,需要给文本设置更高的z-index:
<img class="bg-img" src="assets/black.jpg" alt=""> <p *ngIf="displayText" style="color: white; position: relative; z-index: 10;">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>
内容的提问来源于stack exchange,提问作者KG_1
相关产品推荐
相关产品推荐

