【问题标题】:pass value from child to parent with EventEmiiter and dynamic component angular 6使用 EventEmiiter 和动态组件 angular 6 将值从子级传递给父级
【发布时间】:2019-01-24 10:31:08
【问题描述】:

嗨,我有使用动态组件加载器的动态表单 所以我的父母看起来像这样

<div class="item-form-block-content">
    <div class="form-block">
       <ng-template pf-host></ng-template>
    </div>
</div>

还有许多在 ng-template 中过去的孩子。我想将数据从孩子传递给父母。我正在使用EventEmitter

例如,我的一个子组件

<input type="text" [(ngModel)]="value" (change)="onValueChange(value)"/>

在控制器中

export class childComp implements OnInit {
@Output() someVar = new EventEmitter<any>();

onValueChange(val: any) {
    this.someVar.emit(val);
}}

那么我怎样才能将我的someVar 传递给父母呢?

【问题讨论】:

    标签: angular typescript frontend


    【解决方案1】:

    您只需在父组件模板中的子组件上注册一个事件侦听器,如下所示:

    <child (someVar)="doSomething($event)"></child>
    

    然后在你的父组件中定义doSomething(value: any) {}方法来处理发射的值。

    编辑

    更仔细地查看您的需求,并从this GitHub post 中汲取灵感,可以通过在父组件中手动注册事件侦听器来做到这一点:

    class ParentComponent implements AfterContentInit {
    
        @ContentChildren(ChildComponent)  
        List<ChildComponent> children;
    
        void onSomeValEvent() {
            console.log("Event received!");
        }
    
        ngAfterContentInit() {
            this.children.forEach((ChildComponent child) {
                child.someVal.listen((_) => onSomeValEvent());
            });
        }
    
    }
    

    【讨论】:

    • 你看到我的父组件了吗? ng-template 中有 。根据我的数据结构,有很多孩子。我应该在哪里注册事件监听器?
    • 您必须在发出事件的组件上注册事件监听器(通过@Output 变量)。如果您需要响应来自子组件的事件,这可能意味着更改您的结构。
    • 你可能想看看这个GitHub Issue Comment,它可能对你有用。你只需要通过一些生命周期方法在父组件中手动注册事件监听器。
    • 我不能改变我的结构,因为我必须使用动态组件加载器,因为我的表单包含依赖于数据的组件。
    • 然后我会尝试我之前评论中链接中的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 2019-12-04
    • 2020-09-09
    • 2018-01-15
    • 1970-01-01
    • 2023-01-30
    相关资源
    最近更新 更多