首页 新闻 会员 周边 捐助

angular: 如何向 router-outlet 中的子组件传值

0
悬赏园豆:30 [已解决问题] 解决于 2023-03-20 10:51

比如在订单组件中将支付金额传递给支付组件

order.component.ts

import { Component, OnInit } from '@angular/core';
import { OrderService } from '../services/order.service';

@Component({
  selector: 'app-order',
  template: `
    <router-outlet name="pay"></router-outlet>
  `,
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
  amount!: number;

  constructor(private orderService: OrderService) { }

  ngOnInit(): void {
    this.orderService.createOrder().subscribe(data => {
      this.amount = data.amount;
    });
  }
}

payment-wechat.component.html

<div class='price-tag'>¥{{ amount }}</div>
问题补充:

尝试了2种方法:

1)router-outlet 的 activate 事件

order.component.html

<router-outlet name="pay" (activate)="onActivate($event)"></router-outlet>

order.component.ts

export class OrderComponent implements OnInit {
  order?: Order;

  constructor(private orderService: OrderService) { }

  ngOnInit(): void {
    this.orderService.createOrder().subscribe(order => {
      this.order = order;
    });
  }

  onActivate(component: PaymentWechatComponent) {
    component.amount = this.order?.amount ?? 88;
  }
}

这种方式可以直接更新子组件的属性值,但无法通过 subscribe 更新子组件的属性值,因为 onActivate 执行在先。

参考:Angular : router-outlet and its events

2)EventEmitter 发射事件

order.component.ts

export class OrderComponent implements OnInit {
  order?: Order;

  @Output()
  orderAmount: EventEmitter<number> = new EventEmitter();

  constructor(private orderService: OrderService) { }

  ngOnInit(): void {
    this.orderService.createOrder().subscribe(order => {
      this.order = order;
      this.orderAmount.emit(order.amount);
    });
  }
}

但由于采用 router-outlet 加载子组件,无法通过属性将事件发送给子组件。

order.component.html

<router-outlet name="pay"></router-outlet>

参考:Angular组件——父子组件通讯

dudu的主页 dudu | 高人七级 | 园豆:30757
提问于:2023-03-19 07:36
< >
分享
最佳答案
0

在写完补充问题后突然想到,将方法1与方法2结合(router-outlet activate + EventEmitter)就能解决问题。

在 OrderComponent 的 onActivate 方法中 subscribe EventEmitter

export class OrderComponent implements OnInit {
  order?: Order;

  @Output()
  orderAmount: EventEmitter<number> = new EventEmitter();

  constructor(private orderService: OrderService) { }

  ngOnInit(): void {
    this.orderService.createOrder().subscribe(order => {
      this.order = order;
      this.orderAmount.emit(order.amount);
    });
  }

  onActivate(component: PaymentWechatComponent) {
    this.orderAmount.subscribe(amount =>{
      component.amount = amount;
    });
  }
}

修改代码后搞定!

dudu | 高人七级 |园豆:30757 | 2023-03-20 10:51
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册