1

Suppose, i have a componentA and a componentB

@Component({
  selector: 'appA',
  templateUrl: './appA.html',
  styleUrls: ['./appA.css']
})
export class componentA{
  constructor(private route: Router) { } 
  moveFront() {
    this.route.navigateByUrl('componentB');
  }
}

@Component({
  selector: 'appB',
  templateUrl: './appB.html',
  styleUrls: ['./appB.css']
})
export class componentB{
  constructor(private route: Router) { } 
  moveBack() {
    this.route.navigateByUrl('componentA');
  }
}

now when i call the moveFront() function, componentB gets called but i want to pass some data as well to the component, how can i do that?

both my component is a child component, i want to transfer data to and from the one child component to another child component. how can i do it.

Lijin Durairaj
  • 3,341
  • 11
  • 31
  • 50
  • I would use the store to do this and dispatch whatever I want to be shared between the two to the store right before I navigate to the new component, and when the other component starts up I'd subscribe to that store and get the value. You could also use a service and set a variable in the service and when the second component is created it can actively grab that variable from the service. – Kevin Aug 16 '17 at 15:14
  • Possible duplicate of [Angular2 passing data between two child components](https://stackoverflow.com/questions/38254379/angular2-passing-data-between-two-child-components) – Andrei Matracaru Aug 16 '17 at 15:16
  • Use `ngrx` or a service – Lyubimov Roman Aug 16 '17 at 15:20
  • Possible duplicate of [How do I share data between components in Angular 2?](https://stackoverflow.com/questions/31026886/how-do-i-share-data-between-components-in-angular-2) – AT82 Aug 16 '17 at 16:11

2 Answers2

2

To pass data in Angular you can use @Input to pass data from parent to child @Output to pass data from child to parent

To pass data between sibling components you need either to pass by the parent component or you need to use a service https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

Kld
  • 6,970
  • 3
  • 37
  • 50
2

Another option (if you're only sending string values) is to use Route params. Similar to query params, it has potential for some pretty gnarly looking URLs, but it's an option. First, you would inject the ActivatedRoute:

constructor(private router: Router, private route:ActivatedRoute) { } 

You would use router.navigate instead:

this.router.navigate(['componentB', {myVar:'myValue'}]);

Then in your component, subscribe to the route params:

ngOnInit() {
  this.route.params.subscribe((data) => {
    this.myVar = data.myVar || 'defaultValue';
  });
}

Again, this will only work for strings. Angular calls .toString() on any Object passed using this method. If you're wanting to send more complex data, you should use a service/store.

Corey
  • 5,818
  • 2
  • 24
  • 37