角2动态组件加载器&ngStyle不能一起使用吗? [英] angular 2 Dynamic Component Loader & ngStyle do not work together?
问题描述
我使用的是angular 2动态组件加载程序的确切实现,如下所述: https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html (特别是loadAsRoot实现).
I am using the exact implementation of angular 2's dynamic component loader as described here: https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html (specifically the loadAsRoot implementation).
工作正常.但是,现在我想通过以下方式扩展它:父级具有一定的宽度x高度,我将其传递给服务.然后,在子项中,我订阅该服务,并使用ngStyle渲染子项的尺寸.
It works fine. However, now I want to extend this in the following way: The parent has certain width x height, which I pass to a service. Then, in the child I subscribe to the service, and render the child dimensions with ngStyle.
这在整个应用程序中都可以正常运行,除非我使用动态组件加载器!这不是服务的问题,它在实例化组件时将宽度和高度正确地触发到控制台.但是我放置在ngStyle中的任何内容都不会渲染.
This works fine throughout the app, except when I use dynamic component loader! It is not an issue with the service, it fires the width and height to the console correctly upon instantiation of the component. But whatever I put in ngStyle does not get rendered.
我做错了什么,我有什么解决办法?
What am I doing wrong, and what are my options to work my way around this?
谢谢.
示例代码:
@Component({
selector: 'child-component',
template: '<div [ngStyle]="{'background-color':'red'}">Child</div>'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent (<child id="child"></child>)'
})
class MyApp {
constructor(dcl: DynamicComponentLoader, injector: Injector) {
dcl.loadAsRoot(ChildComponent, '#child', injector);
}
}
bootstrap(MyApp);
调用ngStyle无效.
The invocation of ngStyle has no effect.
推荐答案
dcl.loadAsRoot()
未配置所添加组件的更改检测,但 ngStyle
取决于在启用更改检测时.
dcl.loadAsRoot()
doesn't configure change detection for the added component, but ngStyle
depends on change detection being enabled.
https://github.com/angular/中解释了一种解决方法angular/issues/6223#issuecomment-195155190
this.appRef._loadComponent(cmpRef);
使用私有的 _loadComponent()
.
DynamicComponentLoader
即将被弃用,并由 ViewContainerRef.createComponent()
取代.
DynamicComponentLoader
is about to be deprecated anyway and replaced by ViewContainerRef.createComponent()
.
有关 ViewContainerRef.createComponent()
示例,请参见
查看全文