使用angular 2+从对象获取键和值

时间:2019-06-19 10:17:21

标签: html angular typescript

我有一个像这样的对象:

myComponent.ts

this.detailsStruct = this.newParameter.struct;
 //the value of detailsStruct is:
            //{0: "something",
            // 5: "somethingElse"}

detailsstruct的数据来自我的mongoDb,我想要一个输入表单来显示我的对象的键和值。在html中,我做了类似的事情:

myComponent.html

<div class="form-group" *ngFor="let s of detailsStruct ; let i = index">
 <div class="input-group">
  <input type="text" class="form-control" [ngModelOptions]="{standalone: 
true}"
  [(ngModel)]="s.value" placeholder="" name="{{s[i]}}">
   </div>
</div>

我正在尝试从对象中获取某些东西,但是我写的内容不起作用。 有什么建议么?谢谢

4 个答案:

答案 0 :(得分:0)

您可以使用这种方式,希望这将有助于您处理数据

for (let obj of this.detailsStruct) {
        for (let prop of Object.keys(obj)) {
            console.log("value-" + obj[prop]);
            console.log("key-" + [prop]);
        }
    }

答案 1 :(得分:0)

您可以尝试:

<div class="form-group" *ngFor="let key of objectKeys(detailsStruct) ; let i = index">
 <div class="input-group">
  <input type="text" class="form-control" [ngModelOptions]="{standalone: 
true}"
  [(ngModel)]="detailsStruct[key]" placeholder="" name="{{detailsStruct[key]}}">
   </div>
</div>

ts:

objectKeys = Object.keys;
  detailsStruct = {0: "something",
            5: "somethingElse"}

DEMO

答案 2 :(得分:0)

如果detailsStruct是一个对象,

<div class="form-group" *ngFor="let s of Object.keys(detailsStruct) ; let i = index">
 <div class="input-group">
  <input type="text" class="form-control" [ngModelOptions]="{standalone: 
true}"
  [(ngModel)]="detailsStruct[s]" placeholder="" name="s{{i}}">
   </div>
</div>

答案 3 :(得分:0)

请尝试以下代码:链接https://stackblitz.com/edit/angular-hh82ed

<div class="form-group" *ngFor="let s of detailsStruct ; let i = index">
 <div class="input-group">
  <input type="text" class="form-control" [ngModelOptions]="{standalone: 
true}"
  [(ngModel)]="s[i]" placeholder="" name="{{s[i]}}">
   </div>
</div>

import {AfterViewInit, Component, ElementRef, ViewChild,Renderer2,OnInit} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private renderer: Renderer2, private el: ElementRef) {}
  detailsStruct=[];
  detailsStruct = [{0:"one"},{1:"two"}];
}

谢谢