动态表单上DOM重复ID的Angular 4问题

当我向表单添加1-n动态联系人时,我对DOM抱怨(非致命)有关重复ID的问题.任何建议,将不胜感激.

错误:[DOM]找到2个具有非唯一ID的元素#contactFirstName:

HTML

<div id="contactsSection">
 <div formArrayName="contacts">
   <div class="form-group" *ngFor="let contact of 
       this.editForm.controls.contacts.controls; let i = index" 
         [formGroupName]="i">
       <div>
         <div class="row">
           <div class="form-group col-lg-4 col-md-4 col-sm-4 col-xs-4">
             <label for="contactFirstName">First Name:<sup>*</sup></label>
               <input type="text" class="form-control" id="contactFirstName" 
                    name="contactFirstName" 
                       formControlName="contactFirstName" 
                       required placeholder="First Name">

**Typescript Code:** 
To initialize the form:

    this.editProducerForm = this.fb.group({
      ...
      contacts: this.fb.array([])
    });

To add a contact dynamically to the form I call:

    let control = this.editProducerForm.get('contacts') as FormArray;
    control.push(this.createContact(firstName,...));

which uses this method:

    createContact(firstName: string = '',...): FormGroup {
        let ctc = this.fb.group({
          contactId: id,
          contactFirstName: [firstName, Validators.required ],
          contactMobilePhone: [mobilePhone, CustomValidators.phone ],
          contactAgentLicense: agentlicense,
          contactLastName: [lastName, Validators.required ],
          contactEmail: [email, CustomValidators.email ],
          contactAgentLicenseExpirationDate: licenseExpirationDate,
          contactTitle: [titleUid, Validators.required ],
          ssn: ss
        });
        ctc.markAsUntouched();
        return ctc;
      }

编辑:
我尝试了为每个控件ID添加索引的解决方案.我不相信这是一个可行的解决方案,因为我必须协调代码来访问每个控件,主要是因为如果打破用于动态添加每组控件的formbuilder代码:
   let ctc = this.fb.group({
      contactId:id,
      contactFirstName:[firstName,Validators.required],
      contactMobilePhone:[mobilePhone,CustomValidators.pattern],
      contactAgentLicense:agentlicense,
      contactLastName:[lastName,Validators.required],…

有趣的是,当我通过事件(按钮推送)运行此代码时,DOM不会抱怨.当我作为初始化的一部分运行相同的代码时,它会抱怨.

由于每个FormGroup都有一个唯一的名称,DOM是不是足够智能,以实现一个独特的FormGroup / Control Id是唯一的,而不是查看FormGroup名称的每个Control Id独立?

最佳答案 您可以使用index生成唯一ID:

<label [for]="'contactFirstName' + i">First Name:<sup>*</sup></label>
<input type="text" class="form-control" [id]="'contactFirstName' + i"  ...
点赞