【问题标题】:Angular detect changes through nested componentsAngular 通过嵌套组件检测变化
【发布时间】:2018-02-13 03:28:30
【问题描述】:

我一直在使用角度组件,并且遇到了我有多个嵌套组件的情况,比如 RootComponent->GranParentComponent->ParentComponent->ChildComponent 等 4 个级别。当我对 ChildComponent 进行更改时,我需要使用来自 ChildComponent 的数据调用 RootComponent 中的一些服务。我已经通过组件创建了 EventEmiters 并且它可以工作,但问题是我是否可以在不通过组件与 RootComponent 通信的情况下做到这一点。 提前致谢。

【问题讨论】:

    标签: angular nested components


    【解决方案1】:

    Angular 不支持事件冒泡。如果事件冒泡对您的应用程序很重要,请不要使用 EventEmitter;改为使用本机 DOM 事件。在您的 ChildComponent 中执行以下操作:

    constructor(element: ElementRef){}
    ...
    this.element.nativeElement
    .dispatchEvent(new CustomEvent('myCustomEvent', {foo:bar}));
    

    在您的 RootComponent 中:

    <div (myCustomEvent)= doSomething($event)>
         <GrandParentComponent ></GrandParentComponent>
    </div>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2019-12-07
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    相关资源
    最近更新 更多