如何为Angular2 Component提供动态templateUrl?

时间:2016-03-17 20:30:36

标签: angular angular2-template

我想根据父组件传递的值加载组件templateUrl。我知道可以通过property binding@Input传递给组件,我在下面举例说明myHtml将作为templateName传递。

。但是无法在@Input函数中访问templateUrl值。我认为templateUrl是第一个通过询问HTML来评估的事情,之后所有其他组件代码都会被执行。

就像在角度1中有能力从属性中传递一些值,&然后我可以在templateUrl函数中使用该值作为如下参数。

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

但在Angular2中我无法做到同样的事情,因为templateUrl被强类型为string,因此它不会将函数作为属性。

有没有办法实现这个 OR 我错过了一些简单的事情?

修改

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

这不是我想要的,因为在我的案例中创建具有不同templateUrl的新单独组件并不合理。

我知道如何实现这个目标?

1 个答案:

答案 0 :(得分:3)

一直在与类似的东西挣扎,但不幸的是你无法做到这一点。组件模板在运行时编译。所以,基本上,我会创建一个组件来编译其他子组件(我实际上是这样做的)

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) )
  }
}