【问题标题】:How to iterate object keys using *ngFor?如何使用 *ngFor 迭代对象键?
【发布时间】:2023-03-08 18:07:01
【问题描述】:

我一直在挖掘,发现我可以使用以下方法在对象上使用 *ngFor:

 <div *ngFor="#obj of objs | ObjNgFor">...</div>

ObjNgFor 管道在哪里:

@Pipe({ name: 'ObjNgFor',  pure: false })
export class ObjNgFor implements PipeTransform {
    transform(value: any, args: any[] = null): any {
        return Object.keys(value).map(key => value[key]);
    }
}

但是,当我有这样的对象时:

{
"propertyA":{
    "description":"this is the propertyA",
    "default":"sth"
 },
"propertyB":{
    "description":"this is the propertyB",
    "default":"sth"
 }
}

我不太确定如何提取“propertyA”和“propertyB”,以便可以从 *ngFor 指令访问。有什么想法吗?

更新

我想要做的是呈现以下 HTML:

        <div *ngFor="#obj of objs | ObjNgFor" class="parameters-container">
            <div class="parameter-desc">
                {{SOMETHING}}:{{obj.description}}
            </div>
        </div>

某些东西等于propertyApropertyB(这就是对象的结构)。因此,这将导致:

propertyA:this is the propertyA
propertyB:this is the propertyB

【问题讨论】:

    标签: angular typescript object ngfor


    【解决方案1】:

    只需从管道返回键而不是值,然后使用键访问值:

    let 而不是 beta.17 中的 #

    @Pipe({ name: 'ObjNgFor',  pure: false })
    export class ObjNgFor implements PipeTransform {
        transform(value: any, args: any[] = null): any {
            return Object.keys(value)//.map(key => value[key]);
        }
    }
    
    @Component({
        selector: 'my-app',
        pipes: [ObjNgFor],
        template: `
        <h1>Hello</h1>
     <div *ngFor="let key of objs | ObjNgFor">{{key}}:{{objs[key].description}}</div>    `,
    })
    export class AppComponent {
      objs = {
        "propertyA":{
          "description":"this is the propertyA",
          "default":"sth"
        },
        "propertyB":{
          "description":"this is the propertyB",
          "default":"sth"
        }
      };
    }
    

    Plunker example

    另见Select based on enum in Angular2

    【讨论】:

    • Gunter - 我想向用户显示“propertyA”或“propertyB”。所以我需要以某种方式更换管道
    • 不确定你的意思。取决于您想要显示哪个标准?
    • 不确定您想到的确切用例,但我不明白为什么任何东西都不适用于嵌套对象。
    • 如果objs是异步的,这可以与async管道耦合吗?
    • 当然{{someObservable | async | ObjNgFor}}
    【解决方案2】:

    更新

    6.1.0-beta.1 中引入了KeyValuePipe https://github.com/angular/angular/pull/24319

    <div *ngFor="let item of {'b': 1, 'a': 1} | keyvalue">
      {{ item.key }} - {{ item.value }}
    </div>
    

    Plunker Example

    以前的版本

    你可以试试这样的

    export class ObjNgFor implements PipeTransform {
        transform(value: any, args: any[] = null): any {
            return Object.keys(value).map(key => Object.assign({ key }, value[key]));
        }
    }
    

    然后在你的模板上

      <div *ngFor="let obj of objs | ObjNgFor">
       {{obj.key}} - {{obj.description}}
      </div>
    

    Plunker

    【讨论】:

    • 键值管道正在按 Angular 6 中的键和值顺序排序。我们如何禁用它?
    【解决方案3】:

    或者不创建管道并将对象传递给*ngFor,只需将Object.keys(MyObject) 传递给*ngFor。它返回的结果与管道相同,但没有麻烦。

    关于 TypeScript 文件:

    let list = Object.keys(MyObject); // good old javascript on the rescue
    

    在模板(html)上:

    *ngFor="let item of list"
    

    【讨论】:

    • 谢谢!!!这使它看起来很简单。您应该添加要放在模板部分 btw =) 的内容
    • 简洁的解决方案。我得到了列表中的数字值和字符串值,所以我使用 slice 方法来获取数组的正确一侧:options.slice(options.length / 2)。在这里找到了这个解决方案:stackoverflow.com/questions/38554562/…
    【解决方案4】:

    keys.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'keys' })
    export class KeysPipe implements PipeTransform {
        transform(obj: Object, args: any[] = null): any {
            let array = [];
            Object.keys(obj).forEach(key => {
                array.push({
                    value: obj[key],
                    key: key
                });
            });
            return array;
        }
    }
    

    app.module.ts

    import { KeysPipe } from './keys.pipe';
    
    @NgModule({
      declarations: [
        ...
        KeysPipe
      ]
    })
    

    example.component.html

    <elem *ngFor="let item of obj | keys" id="{{ item.key }}">
        {{ item.value }}
    </elem>
    

    【讨论】:

      【解决方案5】:

      在这个例子中没有使用管道

      *ngFor="let Value bof Values; let i = index"
      
      {{i}}
      

      【讨论】:

      • 完整的代码会有所帮助,而不是其中的一部分。
      猜你喜欢
      • 2017-05-14
      • 1970-01-01
      • 2017-07-05
      • 2022-12-20
      • 1970-01-01
      • 2019-10-26
      • 2017-11-11
      相关资源
      最近更新 更多