【问题标题】:How to use *ngIf in *ngFor in Angular 7?如何在 Angular 7 的 *ngFor 中使用 *ngIf?
【发布时间】:2019-05-17 17:54:25
【问题描述】:

我的 DocumentModel 文档中有多个项目,除了“内容”之外,我都想显示这些项目。我已经尝试通过检查项目名称来排除它,但它仍然显示它:

<p *ngFor="let item of (document | keyvalue)">
    <b *ngIf="item.key != 'content'">{{item.key}}:</b> {{item.value}}
</p>

我也尝试使用不带 '' 的内容,这也不起作用。

如何像在 Java 中一样制作 if(!key.equals("content")) 之类的东西?

文档模型

export class DocumentModel 
{ 
    messageType: string; 
    content: string; 
    failed: boolean; 
    string1: string; 
    string2: string; 
}

【问题讨论】:

  • 您应该使用 TS 文件中的 getter 过滤数组。这样您就不必在模板文件中使用 *ngIf 了。另一种选择是使用管道过滤数组。
  • 谢谢,但这仍然不能解释为什么 *ngIf 不起作用。
  • @karottenbunker 你的文件是什么类型的?
  • if 语句看起来不错。你确定字符串实际上是content 吗?也许它在某个地方有一个特殊字符或空格。
  • 我已经用您提供的模型更新了示例,它按预期工作:(stackblitz)[stackblitz.com/edit/angular-tndqqz].您需要注意,它会将您的对象拆分为道具/值。因此,只有名称为“内容”的属性不会显示,其中分配的实际值将是。

标签: angular ngfor angular-ng-if


【解决方案1】:
You can create pipe to access key

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]});
    }
    return keys;
  }
}
html:
<span *ngFor="let item of content | keys">           
   <b *ngIf="item.key != 'content'">{{item.key}}:</b> {{item.value}}
</span>

或者

为列表中的内容数据编写过滤器。

【讨论】:

    【解决方案2】:

    这是您的初始代码:

    <p *ngFor="let item of (document | keyvalue)">
        <b *ngIf="item.key != 'content'">{{item.key}}:</b> {{item.value}}
    </p>
    

    但如果我查看*ngFor,它似乎可以是documentkeyvalue。所以我的问题是: 你确定documentkeyvaluekey 字段吗?

    【讨论】:

    • 嘿keyvalue是一个管道。见this
    猜你喜欢
    • 2019-09-18
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2016-09-17
    • 2020-06-21
    • 2020-07-18
    • 2018-06-17
    • 1970-01-01
    相关资源
    最近更新 更多