简体   繁体   中英

How to pass data from one child component to another child component in angular2?

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM