I'm having an issue with the DOM complaining (non-fatally) about duplicate IDs when I'm adding 1-n dynamic contacts to a form. Any suggestions would be appreciated.
Error: [DOM] Found 2 elements with non-unique 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;
}
EDIT: I tried the solution of adding the index to each control id. I don't believe this is a viable solution because I have to coordinate the code to access each control and mostly because if breaks the formbuilder code that is used to dynamically add each group of controls: let ctc = this.fb.group({ contactId: id, contactFirstName: [firstName, Validators.required ], contactMobilePhone: [mobilePhone, CustomValidators.pattern ], contactAgentLicense: agentlicense, contactLastName: [lastName, Validators.required ],...
Interestingly, when I run this code via an event (button push), the DOM doesn't complain. When I run the same code as part of initialize, it does complain.
Since each FormGroup has a unique name, is the DOM not smart enough to realize a unique FormGroup/Control Id is unique as opposed to looking at each Control Id indepent of FormGroup name?
You can use index
to generate unique id's:
<label [for]="'contactFirstName' + i">First Name:<sup>*</sup></label>
<input type="text" class="form-control" [id]="'contactFirstName' + i" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With