You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ngTemplateOutlet条件失效及slice管道无显示问题

问题解决

问题1:[ngIf]条件不生效的原因

Angular里同一个元素不能同时使用多个结构型指令,你把[ngIf]和*ngTemplateOutlet放在了同一个ng-container上,这会导致ngIf被忽略,必须把两个指令拆分到不同容器中。

问题2:slice:0:1无内容的原因

如果dynamicFields数组的第一个元素不是'srCreationDate',用slice:0:1截取后自然匹配不到目标值。而且你的需求是只要数组中存在该字段就渲染一次模板,完全不需要循环,直接判断数组是否包含目标值更高效。

修正后的代码方案

方案1:无需循环,直接判断数组包含关系(推荐)

<ng-template #titleCreationDate>
  <div mat-sort-header="srCreationDate"></div>
</ng-template>

<ng-container *ngIf="dynamicFields.includes('srCreationDate')">
  <ng-container *ngTemplateOutlet="titleCreationDate"></ng-container>
</ng-container>

方案2:保留循环(仅当需要用到循环变量时使用)

<ng-template #titleCreationDate>
  <div mat-sort-header="srCreationDate"></div>
</ng-template>

<ng-container *ngFor="let df of dynamicFields | slice:0:1">
  <ng-container *ngIf="df == 'srCreationDate'">
    <ng-container *ngTemplateOutlet="titleCreationDate"></ng-container>
  </ng-container>
</ng-container>

注意:方案2中如果slice:0:1截取的元素不是'srCreationDate',依然不会渲染内容,所以更推荐逻辑清晰、性能更好的方案1。

内容的提问来源于stack exchange,提问作者Uri Perkal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:15:46