向数组添加值的问题

时间:2018-08-29 15:56:43

标签: javascript angular mean-stack angular-forms

我有一个如下界面:        

   import {IRecipients} from "./irecipients";    export interface IDataProcessingSpecification {
 user:string;
 businessID:string;
 recipient:IRecipients[];
   }
   
   
       IRecipient是:        
   export interface IRecipients {
   
 recipientName:string,
 recipientLocation:string[]
   }
   
   
 在这里,我已经初始化了IDataProcessingSpecification类型的变量:        
   generatedDataProcessing:IDataProcessingSpecification=
   {
     user:'',
     businessID:'',
   
     recipient:[{recipientName:'',recipientLocation:[]}],
   
   }
   
收件人是一个或多个。实现我遵循的这个tutorial,即允许一个或多个收件人。因此,接收方包含两个控件,一个用于名称的文本框和一个用于位置的复选框。        当用户从复选框中选择一个位置时,将运行以下代码:

onRecipientLocation(event,location,i) {
   console.log("here " + location+ "  " + i )
   if (event.target.checked) {
   
     this.generatedDataProcessing.recipient[i].recipientLocation.push(location)
   
     console.log("location "+ i+ this.generatedDataProcessing.recipient[i].recipientLocation)
   }
   }
   
 }

因此,对于第一个收件人,复选框功能可以正常工作,但是当通过单击添加添加另一个控件时,在从复选框中进行选择时,我收到此错误“无法读取未定义的属性'recipientLocation'”

编辑,这是HTML代码:

    <div *ngFor="let address of dataProcessingForm.controls.linktodrive.controls; let i=index">
    <div>
      <span>Name the recipient: </span>
      <span *ngIf="dataProcessingForm.controls.linktodrive.controls.length > 1">

        <a (click)="removeLink(i)">    Remove </a></span>
    </div>

    <!-- Angular assigns array index as group name by default 0, 1, 2, ... -->
    <div [formGroupName]="i">
      <input type="text" placeholder="*Enter Recipient" formControlName="recipientName">

      <div>
        <label for="recipientLocation"><h3> Recipient Location:</h3> </label>
          <div *ngFor="let obj of recipientLocation">
            <input type="checkbox"
                   name="recipientLocation"
                   formControlName="recipientLocation"
                   value="{{obj}}"
                   (change)="onRecipientLocation($event,obj,i)"
            >
            {{obj}}
          </div>
        </div>

    </div>

  </div>

    <div><a  (click)="addLink()"> Add </a></div>

1 个答案:

答案 0 :(得分:0)

可能是因为即使i的值增加了,recipient也只有一个对象。尝试推送到0索引或在推送之前添加if条件

if( this.generatedDataProcessing.recipient[i]){
  this.generatedDataProcessing.recipient[i].recipientLocation.push(location)
 }