Angular - Deep nested object models are linked

224 Views Asked by At

I've a Angular application which displays company & contact person information on a text box as below Company Email address:

   <label> Company Email address</label>
   <input type="text" class="form-control" [(ngModel)]="companyInfo.contactInfo.email" value="{{ companyInfo?.contactInfo?.email }}">

&&& Contact Person Email address:

  <label>Contact Email address</label>
  <input type="email" class="form-control" [(ngModel)]="companyInfo.contactPerson.contactInfo.email" value="{{ companyInfo?.contactPerson?.contactInfo?.email }}">

since this info is obtained from a nested object, when the email address of the company is typed in, it reflects in the contact's email address as well. Anything I'm overlooking as component assignment works fine but when input is typed in, it gets mirrored?

3

There are 3 best solutions below

1
kishan On

Hi i got your question it is due to two way binding ngModel is 2-way data binding but it seems the values seems different in this case please check proper names or if possible write your problem in stackblitz.

Or there is another way for it, assign 2 variables in .ts class and reflect the names like this.

   .ts class

    companyEmail: any;
    contactEmail: any;
    this.companyEmail = companyInfo.contactInfo.email;
    this.contactEmail = companyInfo.contactPerson.contactInfo.email;

    .html
<-- For Comapny Email -->
   <input type="text" class="form-control" [(ngModel)]="companyEmail" value="{{ companyEmail }}">

<-- For Contact Email -->

<input type="email" class="form-control" [(ngModel)]="contactEmail" value="{{ contactEmail }}">
3
Ravi Teja Muddada On

I am not sure about your object structure , However I have designed an object based on my understanding from your question and tried the below example

Stackblitz

But, I didn't see that the second value is getting changed , when i am modifying the first value in UI. Its behavior looks good only (You can check the console to verify - i am printing both the values on change call)

0
HARI PRASAD On

Found the issue to be cause of reference to same object while resetting the fields to create a new company form //while resetting

newCompany: Company = new Company(companyName, this.contactInfo,new ContactPerson ( lastName, firstName,this.contactInfo)

replaced with

newCompany: Company = new Company(companyName, ._cloneDeep(this.contactInfo),new ContactPerson ( lastName, firstName,._cloneDeep(this.contactInfo))