Angular中*ngIf失效但ngStyle正常工作,求原因排查
Angular中
*ngIf指令异常问题排查 问题描述
底部组件加载正常,但*ngIf指令存在异常:*ngIf="loading"的元素无法显示,*ngIf="!loading"的元素正常渲染,同时ngStyle指令完全正常工作。
组件TS代码
export class AppComponent implements OnInit { title = 'Anular Application'; products: Iproduct[] = []; parentData: string = "This is parent data"; details: boolean = false; loading: boolean = false; variable: boolean = true; constructor(private productsService: ProductsService) { } ngOnInit(): void { this.loading = true this.productsService.getProducts().subscribe(products => { setTimeout(() => {}, 2000); this.products = products; this.loading = false; this.variable = false; }); } }
HTML代码
<h1 class="text-center" [ngStyle]="{'visibility': loading ? 'visible' : 'hidden' }">Loading ngstyle 23..</h1> <h1 *ngIf="loading" class="text-center">Loading if ..</h1> <h1 *ngIf="!loading" class="text-center">not Loading if ..</h1> <app-product-component [stringHardCode]="'string hardcoded'" [childData]="parentData" *ngFor="let product of products; let i = index" [product]="product"> </app-product-component>
问题原因
核心问题是setTimeout使用错误:你仅定义了一个延迟2秒执行的空回调,但修改loading状态、赋值products的代码是同步执行的。这导致loading被设为true后,几乎瞬间就被改为false,*ngIf="loading"对应的元素根本来不及完成渲染就被销毁,因此无法看到它;而ngStyle是修改已有元素的样式属性,元素本身始终存在,只是visibility快速切换,所以能感知到状态变化;*ngIf="!loading"则因loading快速变为false,正常显示内容。
解决方案
将修改状态和数据赋值的逻辑放入setTimeout的回调函数中,确保加载状态保持2秒,给*ngIf="loading"足够的渲染时间:
export class AppComponent implements OnInit { title = 'Anular Application'; products: Iproduct[] = []; parentData: string = "This is parent data"; details: boolean = false; loading: boolean = false; variable: boolean = true; constructor(private productsService: ProductsService) { } ngOnInit(): void { this.loading = true this.productsService.getProducts().subscribe(products => { setTimeout(() => { this.products = products; this.loading = false; this.variable = false; }, 2000); }); } }
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

