I have 3 components, 1 parent and 2 children.
Parent component:
<p-tabView [(activeIndex)]="index">
<p-tabPanel header="Child1">
<app-child1 [person]="person.data1"></app-child1>
</p-tabPanel>
<p-tabPanel header="Child2">
<app-child2 [person]="person.data2"></app-child2>
</p-tabPanel>
person: any = {};
ngOnInit(): void {
this.personService.getPerson(this.id).then(obj => this.person= obj);
}
Child1 component:
@Input()
person: any;
ngOnInit(): void {
this.person= {age: 0};
}
<p-inputNumber [(ngModel)]="person.age" ></p-inputNumber>
Child2 component:
@Input()
person: any;
ngOnInit(): void {
this.person= {adress: [{number:0}, {number:0}]};
}
<p-inputNumber disabled [(ngModel)]="person.age" ></p-inputNumber>
<p-inputNumber (ngModel)]="person.adress[0].number" ></p-inputNumber>
<p-inputNumber (ngModel)]="person.adress[1].number" ></p-inputNumber>
I would like that if the value of age
in Child1 changes, it will automatically reflect the change in Child2.
Reviewing the code you have shared, it seems that solving your problem is much easier than I imagined.
You can do this by transferring the original data to the children and not making any copies or modifications of that data in them.
The main problem you suffer from is that from child 2 you cannot access the actual property of the parent called
person.age
, since you have overridden the valueperson
inside the component by the content ofperson.data2
the parent.To solve it you would have two options:
person
to each child and access data fromdata1
ordata2
as needed within them.{ address: person.data2.address, age: person.data1.age }
in[person]
son 2.That last solution is the one adopted in the code that I show you. Example:
Also, notice that in the code that I show you below that I have eliminated all the assignments that you made in the children.
Child Component 1
I've removed the method
ngOnInit()
where you override the value ofperson
.Child Component 2
I've removed the method
ngOnInit()
where you override the value ofperson
.parent component
In this component I've changed the way I send the data to the Child 2 component so that it has access to the age and address without having to make any major changes to the child component itself:
You can see an online version of the code at the following URL:
PS: As you have developed your code, from the point of view of the children the content of
person
will be the one that you pass through the attribute of the component with the same name, so for the child component 1 it will beperson.data1
and for the 2 it will beperson.data2
.I think that the most consistent thing would have been to pass the content as
person
complete or to have called the attribute differently.Edition:
address
To dynamically generate a form field for each element, I recommend using a loopNgFor
using one of these two methods:Repeat a component and its content:
Repeat everything encapsulated: