首页 文章

Angular:从动态组件传回数据

提问于
浏览
1

基于cookbook中的example,我正在动态创建组件,如下所示:

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的模板如下所示:

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

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

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

componentRef.changeDetectorRef.detectChanges();

我也读过父母的subscribing to a child's EventEmitter,但只看过使用点击事件的例子 . 更新各种数据(包括文本输入回父母)的更好方法是什么?

我正在使用Angular 4 RC3

1 回答

  • 0

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

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

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

    this.componentRef.instance.observeVariabel.subscribe(result => { this.v = result;  // here observeVariabel is a Observable in dynamic component.
    

相关问题