P
P
Pasler2018-11-26 21:01:36
Angular
Pasler, 2018-11-26 21:01:36

AngularJS6 How to pass data from parent component to child without feedback?

The problem is the following.
The parent component requests data from the server and passes it to the child components.
Template:
List definition:
export class ParentComponent implements OnInit, OnDestroy {
private fullList: any = [];
getFullList() {
return this.fullList;
}
Defined in child component:
export class ChildComponent implements OnInit, OnChanges {
@Input() myList: any;
The problem is that when you change the fields in one of the child components, the data changes in the others. Is it possible to untie this dependency somehow?
@angular/cli 7.0.6

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Mazhekin, 2018-11-26
@mazhekin

getFullList() {
return [...this.fullList];
}

A
Artem Kayun, 2018-12-05
@Kayun

And what do you then do with this changed data? Well, that is, why do you even change the data in the child component that is used in the parent?
This is contrary to unidirectional data flow. If you want to change the data in the child component that you pass via @Input() and then use this changed data in the parent component, then you need to define @Output() for the child components and trigger an event on the child element when you changed the data. At the same time, pass a copy of the object with data to the event. In the parent component, respectively, listen to the data change event on the child components and receive updated data.
This solution is preferable within the framework of angular rather than modifying an object by reference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question