【问题标题】:How can I have dynamic templateUrl for Angular2 Component?我怎样才能拥有 Angular2 组件的动态 templateUrl?
【发布时间】:2016-07-04 10:10:03
【问题描述】:

我想根据从父组件传递的值加载组件templateUrl。我知道 tt 可以通过 property binding 通过 @Input 传递给组件,我在下面给出了示例,其中 myHtml 将作为 templateName 传递。

. 但是在templateUrl 函数中无法访问@Input 值。我认为templateUrl 是通过请求 HTML 来评估的第一件事,然后执行所有其他组件代码。

就像 angular 1 一样,它能够从属性中传递一些值,然后我可以在 templateUrl 函数中使用该值作为参数,如下所示。

templateUrl: function(element, attrs){
    //was getting value
    return '/app/templates/'+ attrs.myTemplateName + '.html'
}

但是我在 Angular2 中不能做同样的事情,因为 templateUrl 被强类型化为 string 所以它不会将函数作为属性。

有没有办法做到这一点我错过了一些简单的事情?

编辑

我已经看过this answer,这不是我想要的。在引用的答案中,它使用加载另一个组件的DynamicComponentLoader 渲染 DOM。

这不是我想要的,因为在我的情况下,为具有不同的 templateUrl 创建新的单独组件没有意义。

知道如何实现吗?

【问题讨论】:

  • @MarkRajcok 我已经完成的方式标记为重复答案,手动创建模板/assign independant component。并且不想创建一个具有不同templateUrl 的新component,这听起来对我来说是重复的......如果我仍然错过了什么,请指导我......
  • Dynamic templateUrls 不受支持,根据另一个问题的答案(这就是我最初关闭这个问题的原因)。如果你想要一个动态模板,我相信你必须使用DynamicComponentLoader。似乎您正在尝试创建一个通用组件,它可以有许多不同的可能模板。这听起来像是 DynamicComponent 加载器的工作,不是吗?
  • @MarkRajcok 正确,这似乎是一种解决方法,但需要有样板代码,尽管感谢您的解释。但是在链接的答案中,我看到对于每个templateUrl,我需要创建一个单独的FakeComponent 以获得不同的templateUrl,因此对于3 个templateUrl,我需要创建三个FakeComponent,这对我来说听起来不太好(不需要样板代码)。我认为应该是比这更好的方法。我想错了吗?
  • @AngelAngel 谢谢..建议的答案在引用的链接上,我在添加问题之前已经尝试过那个东西.. Angular2 没有这样的选项让function 用于templateUrl,因为@ 987654345@ 元数据templateUrl 属性被强类型化为string,我已经在我的问题中提到了这件事。谢谢:-)

标签: angular angular2-template


【解决方案1】:

一直在为类似的事情苦苦挣扎,但不幸的是你不能这样做。组件模板在运行时编译。所以,基本上,我会制作一个编译其他子组件的组件(我实际上是这样做的)

DynamicComponentLoader 已弃用。您需要使用ComponentResolver 类来加载主组件中的其他组件,如下所示:

function makeComponent( selector, template, ...more )
{
  @Component({ selector: selector, template: template })
  class FakeComponent {}
  return FakeComponent;
}

@Component({ ... })
export class MainCmp implements OnInit
{
  // place to insert
  @ViewChild('viewChild', {read: ViewContainerRef}) viewChild: ViewContainerRef;

  constructor(private compiler: ComponentResolver){}
  // or OnChanges, or event binding.. should work

  ngOnInit()
  {
    // decide on your custom logic here, get you @Input, whatever...

    // and you can actually make some custom dynamic component...
    let childCmp = makeComponent( custom, stuff, here );

    // compile then insert in your location, defined by viewChild
    this.compiler.resolveComponent( childCmp )
      .then( (compFactory:ComponentFactory) => this.viewChild.createComponent(compFactory) )
  }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 2023-01-22
  • 2015-09-26
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多