Current Situation:
I have a parent
and a child
component.
The parent
initializes the child
's data using its @Input
. And the child
notifies the parent, when the user edited the data using the @Output
. And because the data is immutable, the child
has to send the data along with that notification.
When the parent
got notified, it will check if the submitted data is valid, and then will set it (this will propagate the new value to some other child components as well).
The Problem:
When setting the new data inside the parent
, it will of course also give it to the child
component which just submitted the data. This will trigger the child
's ngOnChanges
, which then triggers a repaint of the UI.
Some Background:
The parent
has several different child
components, which all rely on the same myItem
data and can edit this data and then notify the parent
on change.
Here's a simplified version of the code, that should show up the problem.
Parent Component:
template:
<child [input]="myItem" (output)="onMyItemChange($event)">
code:
ngOnInit() {
this.myItem = getDataViaHTTP();
}
onMyItemChange($event) {
if($event.myItem.isValid()) {
this.myItem = $event.myItem;
}
}
Child Component:
template:
<input [(ngModel)]="myItem.name" (ngModelChange)="modelChange($event)">
code:
@Input() input;
@Output() output = new EventEmitter();
myItem;
ngOnChanges(changes) {
this.myItem = changes.input.currentValue.toMutableJS();
}
modelChange($event) {
this.output.emit(this.myItem.toImmutableJS())
}
As you can see, the child
component takes the data from the @Input
and makes it mutable. And before sending it back to the parent
it will make it immutable again.
Is there any pattern to prevent these circular events?
I now came up with a working (but very ugly solution):
child
stores the last emitted value withinmodelChange
when
ngOnChanges
gets called, we can compare the references of those objectsif references are equal, then this particular
child
component created the valueSimplified code example:
It's working as expected, but I still wonder if there's a nicer way using less code.
Maybe it's possible to work around this using
Observable
s for the@Input() input
?I can't think of a way to break the away from the circle if we stick with bi-directionaly event trigger. Especially with multiple children.
Method 1
One way I can think of is both parent and children use a share data service. Data is change once and for all, as all parties are using the same data.
globaldata.service.ts
app.module.ts(assume this is your root module)
parent.component.ts (assuming non-root, multiple instances, part of app.module)
child.component.ts
Method 2 - broadcast queue
Use RxJs subject subscription, like a broadcast queue. I have actually created a package with example:
https://github.com/J-Siu/ng2-simple-mq
https://github.com/J-Siu/ng2-simple-mq-example
The idea:
Parent (assuming non-root, multiple instances, part of app.module)
Child