如何在Ionic 4中将项目添加到JSON数组

时间:2019-10-21 18:31:41

标签: angular ionic4

我有一个包含以下数据的json数组。

  "civilWorks": [
    { 
      question: ' question 1. ', 
      radio_name: 'radio_1',
      radio_input: '',
      text_name: 'text_1',
      text_input: '',
      id: 'id1'       
    },

    { 
      question: ' Question 2.', 
      radio_name: 'radio_2',
      radio_input: '','',  
      text_name: 'text_2',
      text_input: '',
      id: 'id2'    
    }
  ]

我正在尝试使用按钮通过方法添加更多文本输入。我已经能够通过addMore方法成功添加新问题,但无法添加到现有问题中。

我的html如下。

html

<ion-card *ngFor="let item of form; let i=index;">
  <ion-card-content>
    <div class="question">
        {{ item.question }}
    </div>

    <ion-radio-group name="{{item.radio_name}}" [(ngModel)]="form[i].radio_input">         
      <ion-row class="radio-tags">
        <ion-item class="radio-tag" lines="none">
          <ion-label class="tag-label">compliant</ion-label>
          <ion-radio value="compliant" (click)="closeSelect(i)"></ion-radio>
        </ion-item>
        <ion-item class="radio-tagtwo" lines="none">
          <ion-label class="tag-label">non-compliant</ion-label>
          <ion-radio value="non-compliant" (click)="openSelect(i)"></ion-radio>
        </ion-item>
      </ion-row>
    </ion-radio-group>

    <div *ngIf="show[i]">
      <ion-button (click)="addMore(i)" expand="full" color="primary">Add more text boxes</ion-button><br>
      <ion-item>
          <ion-label position="floating" >Text</ion-label>
          <ion-textarea name="{{item.text_name}}" [(ngModel)]="form[i].text_input"></ion-textarea>
        </ion-item>    
    </div>
  </ion-card-content>
</ion-card>

我的addMore方法如下。我无法深入研究this.form并在现有问题中添加信息。

ts

addMore(index: number){
  const newFormItem = this.form;
  newFormItem.push(
    {
      'text2_name': 'text_3',
      'text2_input': '',
    }
  );
  console.log("new items", newFormItem);
}

日志输出的图像

image of log file

2 个答案:

答案 0 :(得分:1)

请在此处查看:您输入的addMore函数错误。

<div class="question">
   {{ item.question }} // here item has question property
</div>

像这样更改它,然后它应该起作用。

addMore(index: number){
  const newFormItem = this.form;
  newFormItem.push(
    { 
      question: ' Question 3.', 
      radio_name: 'radio_3',
      radio_input: '','',  
      text_name: 'text_3',
      text_input: '',
      id: 'id3'    
    }
  );
  console.log("new items", newFormItem);
}

答案 1 :(得分:1)

您的form是JS对象,而不是JSON。从JSON输出中可以看出,表单被键入为对象数组(object [])。您可以在索引位置的对象数组中添加新的键值对。

addMore(index: number){
  // bracket notation
  this.form[index]['text2_name'] = 'text_3';
  // dot notation
  this.form[index].text2_name = 'text_3';
}