【问题标题】:How to pass data from one child component to another child component in angular2?如何将数据从一个子组件传递到angular2中的另一个子组件?
【发布时间】:2018-01-24 19:20:18
【问题描述】:

假设,我有一个组件A和一个组件B

@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');
  }
}

现在当我调用 moveFront() 函数时,componentB 被调用,但我也想将一些数据传递给组件,我该怎么做?

我的组件都是子组件,我想将数据传输到一个子组件和另一个子组件。我该怎么做。

【问题讨论】:

标签: angular


【解决方案1】:

要在 Angular 中传递数据,您可以使用 @Input 将数据从父母传递给孩子 @Output 将数据从孩子传递给父母

要在兄弟组件之间传递数据,您需要通过父组件传递,或者您需要使用服务https://angular.io/guide/component-interaction#parent-interacts-with-child-via-local-variable

【讨论】:

    【解决方案2】:

    另一个选项(如果你只发送字符串值)是使用路由参数。与查询参数类似,它有可能生成一些看起来很粗糙的 URL,但它是一个选项。首先,您将注入ActivatedRoute:

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

    您可以改用router.navigate:

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

    然后在你的组件中,订阅路由参数:

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

    同样,这仅适用于字符串。 Angular 在使用此方法传递的任何对象上调用 .toString()。如果您想发送更复杂的数据,您应该使用服务/存储。

    【讨论】:

    • 使用 JSON 字符串,你有大量可用数据
    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2020-05-02
    • 1970-01-01
    • 2020-05-08
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多