【问题标题】:Getting error with ngIf in Angular在 Angular 中使用 ngIf 出错
【发布时间】:2018-04-14 19:28:23
【问题描述】:

我正在使用 Angular,我想显示来自 json 形式的变量的数据 .我可以为 *ngfor 做到这一点,但我也想设置一个条件来检查 msg.who=="Bot"。我正在使用:

<div class="UserWrapper" *ngFor="let msg of msgs" ngIf="msg.who == 'User ">
    <div class=""></div>
        <div class = "speech-bubble1 z-depth-5"><p>{{msg.msg}}</p>
            <p class="timeRight">{{msg.time}}</p>
    </div>
 </div>

如果另一种方式,我不知道如何使用 ng,但这样做时我收到以下错误。

ERROR Error: StaticInjectorError(AppModule)[NgForOf -> TemplateRef]: 
StaticInjectorError(Platform: core)[NgForOf -> TemplateRef]: 
NullInjectorError: No provider for TemplateRef!

如何检查给定的条件

【问题讨论】:

    标签: angular angular-ng-if


    【解决方案1】:

    您不能在同一个 element 上使用 ngForngIf,因此请将其替换为 @987654324 @,还有一些错误,例如 *ngIf 而不是 ngIf,你应该使用 ===也检查类型

    如下更改您的代码,

    <ng-container *ngFor="let msg of msgs">
      <div *ngIf="msg.who === User"  class=""> 
            <div class = "speech-bubble1 z-depth-5"><p>{{msg.msg}}</p>
            <p class="timeRight">{{msg.time}}</p>
      </div>
    </ng-container>
    

    【讨论】:

    • 但是我如何检查 msg.who 是 but 还是 user 的条件
    • @alia 关于=== 注释,有趣的是,"1" == 1.ts 文件中时会抛出编译错误 (Operator '==' cannot be applied to types 'string' and 'number'.),但在使用时会评估为 true一个模板。因此,您可能应该将类型敏感的评估提取到一个单独的函数中并引用它。 @Sajeetharan 同意吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2018-10-01
    相关资源
    最近更新 更多