如何将@Input与使用ComponentFactoryResolver创建的组件一起使用? [英] How do you use @Input with components created with a ComponentFactoryResolver?

查看:107
本文介绍了如何将@Input与使用ComponentFactoryResolver创建的组件一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用一种方法在动态创建的Angular 2组件上定义@Input属性?

Is there a method that can be used to define an @Input property on an Angular 2 component that's created dynamically?

我正在使用 ComponentFactoryResolver 在容器组件中创建组件.例如:

I'm using the ComponentFactoryResolver to create components in a container component. For example:

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName);

let componentRef = entryPoint.createComponent(componentFactory);

在组件HTML中,"entryPoint"的含义如下:

Where "entryPoint" is something like this in the component HTML:

<div #entryPoint></div>

并在我的容器组件中定义为:

And defined in my container component with:

@ViewChild('entryPoint', { read: ViewContainerRef } entryPoint: ViewContainerRef;

这很好用,但是我找不到在新创建的组件上使用@Input属性的方法.我知道您可以在组件类上显式设置公共属性,但这似乎不适用于ng-reflect.在进行此更改之前,我有一个用"@Input()"修饰的"selected"属性,该属性使Angular向DOM添加以下内容:

This works well, but I can't find a way to make an @Input property work on the newly created component. I know that you can explicitly set public properties on the component class, but this doesn't seem to work with ng-reflect. Prior to making this change I had a "selected" property decorated with "@Input()" that caused Angular to add the following to the DOM:

<my-component ng-reflected-selected="true"></my-component>

有了这个,我能够动态更新标记以切换CSS类:

With this in place I was able to dynamically update the markup to switch a CSS class:

<div class="header" [class.active-header]="selected === true"></div>

基于一些搜索,我能够找到一种使"@Output"正常工作的方法,但是我还没有为@Input找到任何东西.

Based on some searching I was able to find a method to make "@Output" work as expected, but I've yet to find anything for @Input.

让我知道其他上下文是否有帮助,我很乐意添加它.

Let me know if additional context would be helpful and I'd be happy to add it.

推荐答案

否,Angular2绑定仅适用于静态添加到组件模板的组件和指令.

No, Angular2 bindings only work with components and directives statically added to the template of a component.

对于所有其他情况,请使用共享服务,如

For all other situations use shared services like explained in https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

您也可以使用

let componentRef = entryPoint.createComponent(componentFactory);
componentRef.instance.someProp = 'someValue';
componentRef.instance.someObservableOrEventEmitter.subscribe(data => this.prop = data);

这篇关于如何将@Input与使用ComponentFactoryResolver创建的组件一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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