Angular: passing data back from dynamic component

南楼画角 提交于 2019-12-07 23:02:02

问题


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's template would look like this:

<input type="text" [(ngModel)]="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();

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?

I am using Angular 4 RC3


回答1:


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).


来源:https://stackoverflow.com/questions/42848369/angular-passing-data-back-from-dynamic-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!