【问题标题】:How to provide data to a @Component through DynamicComponentLoader?如何通过 DynamicComponentLoader 向@Component 提供数据?
【发布时间】:2016-01-21 00:55:41
【问题描述】:

我需要通过DynamicComponentLoader 向组件提供视图数据,如果可能的话通过构造函数,但为此我需要绑定数据。

var bindings = Injector.resolve([bind(Model).toValue(viewModel)]);
this.loader.loadIntoLocation(component, eleRef, anchor, bindings)

这可行,但我需要将数据绑定到 Injection-System 中,因此我不确定这是否正确。

另一种设置数据的方法是使用promise:

this.loader.loadIntoLocation(component, eleRef, anchor).then(componentRef=> {
  var comp:AbstractComponentBase = componentRef.instance;
  comp.model = viewModel;
});

这也可以,但模型在初始化期间是null(或伪值),这可能是@ViewChildrenafterViewInit() 的问题。

还有其他方法可以为使用DynamicComponentLoader 创建的组件提供数据吗?

【问题讨论】:

    标签: angular


    【解决方案1】:

    我正在试验一个页面容器组件,该组件需要响应路由更改以支持类似多文档界面的功能。我所有的路由都映射到这个公共容器组件,页面的标识是用 RouteData 定义的。我还有一个通用页面组件(用于支持我正在转换的应用程序中基于 jquery 的旧页面),它将被动态创建,并且 RouteData 将被注入其构造函数中。

    当我意识到在第一个页面加载后,后续路由更改不会导致相应的 RouteData 在公共页面组件的新实例中可用时,我遇到了类似的需求。在每次路由更改时,新页面实例将看到与第一页相对应的路由数据值,而不是当前页面。

    为了解决这个问题,我显式更改了可用于动态创建的页面的 RouteData 提供程序,如下所示:

    var providers = Injector.resolve([new Provider(RouteData, { useValue: next.routeData })]);
    this.loader.loadIntoLocation(LegacyPanelComponent, this.element, 'panels', providers)
        .then(componentRef => this.setActiveRoute(nextRoute, componentRef));
    

    我认为您可以使用类似的方法将数据传递给您的动态组件,其中自定义类实例可用作提供者。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多