Angular:从动态组件传回数据 [英] Angular: passing data back from dynamic component

查看:29
本文介绍了Angular:从动态组件传回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于食谱中的示例,我正在像这样动态创建组件:

Based on an example in the cookbook, I am creating components dynamically like this:

    private loadComponent(): void {
        const componentFactory = this.factoryResolver.resolveComponentFactory(MyInputComponent);

        const viewContainerRef = this.componentHost.viewContainerRef;
        viewContainerRef.clear();

        const componentRef = viewContainerRef.createComponent(componentFactory);
        (<IComponent>componentRef.instance).data = data;
}

MyInputComponent 的模板如下所示:

MyInputComponent's template would look like this:

<input type="text" [(ngModel)]="data.inputProp">

当用户输入输入时,我需要更新父级中 data.inputProp 的值.

I need to update the value of data.inputProp in the parent when the user types in the input.

我在一些例子中看到过这个,但不确定它的作用是什么?

I have seen this in some examples, but not sure what it does?

componentRef.changeDetectorRef.detectChanges();

我还阅读了关于订阅到父级中孩子的 EventEmitter ,但只看到了使用点击事件的例子.将包括文本输入在内的各种数据更新回父级的更好方法是什么?

I've also read about subscribing to a child's EventEmitter in the parent, but only seen examples of that using click events. What is the better approach for updating all kinds of data including text inputs back to the parent?

我使用的是 Angular 4 RC3

I am using Angular 4 RC3

推荐答案

如果您想将数据发送到动态创建的组件.

If you want to send data to dynamically created component.

this.componentRef.instance.variableName = 'abc';  // here variableName is a variable of dynamic component.

如果你想从动态创建的组件中获取数据.

If you want to get data from dynamically created component.

this.componentRef.instance.observeVariable.subscribe(result => { this.v = result;  // here observeVariable is an Observable in dynamic component(ie. this.componentRef).

这篇关于Angular:从动态组件传回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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