AngularDart:如何将事件从子组件传递到二级父组件 [英] AngularDart: How do you pass an event from a Child component to a second level parent

查看:31
本文介绍了AngularDart:如何将事件从子组件传递到二级父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 StreamControllers 与事件一起使用,并且基本上我有一个 3 级组件层次结构,可以将它们称为 A、B、C.层次结构是 A -> B -> C.

I am using StreamControllers with Events, and essentially I have a 3 level component heirarchy lets call them, A,B,C. The heirarchy is A -> B -> C.

事件的起源在 c 中,我希望事件由 A 处理.

The origin of the event is in c and i want the event to be processed by A.

我知道使用 @Output 的直接父级 -> 子级关系很容易做到这一点,但不确定如何正确处理多个级别.

I know this is rather easy to do with a direct parent -> child relationship using @Output but not sure how to properly handle multiple levels upwards.

推荐答案

感谢提问.

有几种方法可以做到这一点.

There are a couple ways to do this.

(1) 在 B 中创建一个从 C

(1) Create an event handler in B that forwards from C

@Component(
  selector: 'b',
  directives: const [C],
  template: '<c (event)="cDidEvent()"></c>',
)
class B {
  final _onEvent = new StreamController();
  Stream get onEvent => _onEvent.stream;

  void cDidEvent() {
    _onEvent.add(null);
  }
}

(2) 使用依赖注入.

(2) Use dependency injection.

这需要组件之间更深的耦合,因此它不适用于所有设计,但在某些情况下可能有意义.

This requires deeper coupling between components, so it won't be appropriate for all designs, but it could make sense in some scenarios.

abstract class OnEvent {
  /// Called when an event happens.
  void onEvent();
}

@Component(
  selector: 'a',
  directives: const [B],
  template: '<b></b>',
  providers: const [
    const Provider(OnEvent, useExisting: A),
  ],
)
class A implements OnEvent {
  @override
  void onEvent() {
    print('>>> An event was triggered!');
  }
}

class C {
  final OnEvent _eventHandler;

  C(this._eventHandler);

  void onSomeAction() {
    _eventHandler.onEvent();
  }
}

这篇关于AngularDart:如何将事件从子组件传递到二级父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆