Passing data into "router-outlet" child components
<router-outlet [node]="..."></router-outlet>
is just invalid. The component added by the router is added as sibling to <router-outlet>
and does not replace it.
See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
@Injectable()
export class NodeService {
private node:Subject<Node> = new BehaviorSubject<Node>([]);
get node$(){
return this.node.asObservable().filter(node => !!node);
}
addNode(data:Node) {
this.node.next(data);
}
}
@Component({
selector : 'node-display',
providers: [NodeService],
template : `
<router-outlet></router-outlet>
`
})
export class NodeDisplayComponent implements OnInit {
constructor(private nodeService:NodeService) {}
node: Node;
ngOnInit(): void {
this.nodeService.getNode(path)
.subscribe(
node => {
this.nodeService.addNode(node);
},
err => {
console.log(err);
}
);
}
}
export class ChildDisplay implements OnInit{
constructor(nodeService:NodeService) {
nodeService.node$.subscribe(n => this.node = n);
}
}
Günters answer is great, I just want to point out another way without using Observables.
Here we though have to remember that these objects are passed by reference, so if you want to do some work on the object in the child and not affect the parent object, I would suggest using Günther's solution. But if it doesn't matter, or actually is desired behavior, I would suggest the following.
@Injectable()
export class SharedService {
sharedNode = {
// properties
};
}
In your parent you can assign the value:
this.sharedService.sharedNode = this.node;
And in your children (AND parent), inject the shared Service in your constructor. Remember to provide the service at module level providers array if you want a singleton service all over the components in that module. Alternatively, just add the service in the providers array in the parent only, then the parent and child will share the same instance of service.
node: Node;
ngOnInit() {
this.node = this.sharedService.sharedNode;
}
And as newman kindly pointed, you can also have this.sharedService.sharedNode
in the html template or a getter:
get sharedNode(){
return this.sharedService.sharedNode;
}