【问题标题】:angular 2 Dynamic Component Loader & ngStyle do not work together?angular 2 Dynamic Component Loader & ngStyle 不能一起工作?
【发布时间】:2016-10-02 13:29:38
【问题描述】:

我正在使用 Angular 2 的动态组件加载器的确切实现,如下所述:https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html(特别是 loadAsRoot 实现)。

它工作正常。但是,现在我想通过以下方式扩展它:父级具有一定的宽度 x 高度,我将其传递给服务。然后,在孩子中订阅服务,并使用 ngStyle 渲染子维度。

这在整个应用程序中都可以正常工作,除非我使用动态组件加载器!这不是服务的问题,它会在组件实例化时正确地向控制台触发宽度和高度。但是我在 ngStyle 中输入的任何内容都不会被渲染。

我做错了什么,我有哪些选择可以解决这个问题?

谢谢。

编辑:

示例代码:

@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 的调用没有效果。

【问题讨论】:

  • 你把ngStyle放在哪里?请显示一些代码。您如何使用 DCL?

标签: angular


【解决方案1】:

dcl.loadAsRoot() 不会为添加的组件配置更改检测,但ngStyle 取决于启用的更改检测。

解决方法在https://github.com/angular/angular/issues/6223#issuecomment-195155190中进行了说明

this.appRef._loadComponent(cmpRef);

使用私有_loadComponent()

DynamicComponentLoader 无论如何都将被弃用,取而代之的是ViewContainerRef.createComponent()

有关ViewContainerRef.createComponent() 的示例,请参阅Angular 2 dynamic tabs with user-click chosen components

【讨论】:

  • 我无法仅从错误消息中分辨出来。 type 参数是因为静态检查的严格设置。 type 参数在技术上不是必需的。
  • 嗨,Gunter,我删除了我的评论,因为我设法解决了它。出于某种原因,我需要导入 ComponentFactory,这在您的 plunker 中显然不需要。我想问你:你的plunker确实解决了我的问题。但是,如果您通过服务获取类型数组,并且这些数组因用户而异,也许您可​​以建议我。如何避免必须导入所有可能的组件?谢谢
  • 如果你使用ComponentFactory,你必须导入它。 Plunker 中的配置忽略了缺少的类型,您的本地配置可能更严格。您必须在“某处”导入所有可能的组件。您可以创建一个允许按名称获取类型的类,然后您只需导入设置该类的所有组件。您实际使用地图的地方,您只需导入和注入类。
  • class Components { c1:Type = Component1; c2:Type = Component2; } 他们注入组件并以components.c2 访问组件。 (我希望Type这个类实际上是一个引用类的变量的东西。我不太了解TS,因为我自己使用Dart。)
猜你喜欢
  • 2020-08-31
  • 1970-01-01
  • 2016-07-19
  • 2017-07-15
  • 1970-01-01
  • 2017-12-18
  • 2017-01-18
  • 2019-10-08
  • 2017-02-21
相关资源
最近更新 更多