简体   繁体   English

如何将 object 与 Angular 中的键和值绑定?

[英]How to bind an object with keys and values in Angular?

In Typescript I receive data from ASP.NET Core C# Dictionary (It is not a Map but it has keys and values ie I can run Object.keys(data) and Object.values(data) ).在 Typescript 中,我从 ASP.NET 核心 C# Dictionary接收data (它不是Map但它有键和值,即我可以运行Object.keys(data)Object.values(data) )。

In HTML I have an Angular component which binds to data .在 HTML 中,我有一个绑定到data的 Angular 组件。 I cant figure out the syntax for binding the key and values array.我无法弄清楚绑定键和值数组的语法。

Roughly:大致:

      <dx-gallery [dataSource]="data">
        <div *dxTemplate="let i of 'item'">
          <dx-chart [dataSource]="i.value">
            <dxi-series [name]="i.key" valueField="value.X"

i is a single key value pair (a string and an array) from whole data collection. i是来自整个数据集合的单个键值对(一个字符串和一个数组)。 in C# I would write i.Key and i.Value but it doesnt work in Typescript for me (the component doesnt see data to display).在 C# 中,我会编写i.Keyi.Value ,但它在 Typescript 中对我不起作用(组件看不到要显示的数据)。

I need to bind key and X我需要绑定keyX

the data is {A: Array, B: Array} where Array is MyObj[]数据是 {A: Array, B: Array} 其中 Array 是 MyObj[]

you can loop over an object, by grabbing it's keys.您可以通过抓住它的键来遍历 object。

eg例如

// component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  data = {
    prop1: 'a',
    prop2: 'b'
  };
  keys = Object.keys(this.data);
}

-- --

//component.html
<p *ngFor="let k of keys">
  {{k}} : {{data[k]}}
</p>

Alternatively, you can expose the Object class to the html template and grab the keys and values as needed.或者,您可以将Object class 公开给 html 模板并根据需要获取键和值。

eg例如

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  data = {
    prop1: 'a',
    prop2: 'b'
  };
  keys = Object.keys(this.data);
  Object = Object;
}

-- --

// html
<p *ngFor="let k of Object.keys(data)">
  {{k}} : {{data[k]}}
</p>

However, adding function calls to your html can sometimes be less performant than just storing the the var "keys" in the ts file, as the function will reevaluate with every change detection cycle.但是,将 function 调用添加到您的 html 有时可能比仅将 var“keys”存储在ts文件中性能更低,因为 function 将在每个更改检测周期重新评估。

You could try the native KeyValuePipe from Angular: here您可以尝试来自 Angular 的原生KeyValuePipe这里

It would look like this, and allow you to refer to the entries with key and value :它看起来像这样,并允许您使用keyvalue引用条目:

<dx-gallery [dataSource]="data">
  <div *dxTemplate="let i of item | keyvalue">
     <dx-chart [dataSource]="i.value">
       <dxi-series [name]="i.key" valueField="value.X">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM