简体   繁体   English

如何将数据从一个子组件传递到angular2中的另一个子组件?

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

Suppose, i have a componentA and a componentB 假设我有一个componentA和一个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? 现在,当我调用moveFront()函数时,componentB被调用但我想将一些数据传递给组件,我该怎么做?

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 要在Angular中传递数据,您可以使用@Input将数据从父传递到子@Output以将数据从子传递到父级

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 要在兄弟组件之间传递数据,您需要通过父组件传递,或者您需要使用服务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. 另一个选项(如果您只发送字符串值)是使用Route params。 Similar to query params, it has potential for some pretty gnarly looking URLs, but it's an option. 与查询参数类似,它有一些看起来非常粗糙的URL的潜力,但它是一个选项。 First, you would inject the ActivatedRoute : 首先,您将注入ActivatedRoute

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

You would use router.navigate instead: 你会使用router.navigate

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. Angular在使用此方法传递的任何Object上调用.toString() If you're wanting to send more complex data, you should use a service/store. 如果您想发送更复杂的数据,则应使用服务/商店。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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