【问题标题】:Parent component listen focus on input contained in child component父组件监听子组件中包含的输入
【发布时间】:2018-05-25 09:15:22
【问题描述】:

我在另一个组件(父级)的页面 html 中有一个组件(子级):

<div>
   <child-component (focusEmit)="startAnimation()"></child-component>
</div>

在子组件中有一个输入:

<input type="text" (focus)="focusFunction()"/>

focusFunction() 向做某事的父级发出一个事件。

我不想以这种方式解决这个用例。我希望子组件是干净的(因为我还有其他嵌套组件,这个用例被简化了,我不想要一长串输出发射)。

还有另一种方法是父级在其子级组件中包含的输入中捕获事件焦点?

【问题讨论】:

    标签: angular parent-child communication angular-components onfocus


    【解决方案1】:

    您可以使用主题(rxJs)http://reactivex.io/rxjs/manual/overview.html#subject 这是 EventEmitter 的替代品。


    通过@Output eventEmitter 可以这样做

    子组件

    @Output() focusEmit = new EventEmitter<any>();
    
    focusFunction() {
       this.focusEmit.emit(true);
    }
    

    父组件

    HTML

     <child-component (focusEmit)="startAnimation(event)"></child-component>
    

    组件.ts

    startAnimation($event) {
        // Handle your code
    }
    

    带有 ViewChild 模式

    父组件

    <child-component  #childAttr></child-component>
    
    @ViewChild("childAttr") childAttr;
    childAttrId : string;
    
    startAnimation() {
        this.childAttrId  = childAttr.id;
    }
    

    但您的子组件保持不变

    focusFunction() {
       this.id = "focus triggered";
    }
    

    【讨论】:

    • 我不会通过服务。在这一点上,我更喜欢使用发射事件。
    • 哦,好吧,我将修改我的答案以处理 eventEmitter
    • 对不起,我可能没有说清楚。这已经是我的解决方案了。但我问是否有其他解决方案,其中父母可以捕获其子组件中包含的事件。通过这种方式,孩子保持清洁,父母处理事件。
    • 如果你有兴趣通过事件来处理它,那么它是唯一的方法。
    • 您也可以使用@ViewChild。我将使用 viewChild 编辑我的答案
    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2021-08-10
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 2019-07-20
    相关资源
    最近更新 更多