我想根据从父组件传递的值加载组件templateUrl.我知道可以通过@Input通过属性绑定到组件,我在下面举例说明my
Html将作为templateName传递.
但是没有能力访问templateUrl函数中的@Input值.我认为templateUrl是第一个通过询问HTML来评估的东西,之后所有其他组件代码都被执行了.
就像角度1一样,能够从属性中传递一些值,&然后我可以在templateUrl函数中使用该值作为如下参数.
templateUrl: function(element,attrs){ //was getting value return '/app/templates/'+ attrs.myTemplateName + '.html' }
但同样的事情我不能在Angular2中做,因为templateUrl被强类型化为字符串,因此它不会将函数作为属性.
有没有办法实现这一点或我错过了一些简单的东西?
编辑
我已经看过this answer这不是我想要的.在参考答案中,它使用DynamicComponentLoader渲染DOM,后者加载另一个组件.
这不是我想要的,因为在我的情况下创建具有不同templateUrl的新单独组件是没有意义的.
知道我该如何实现这个?
解决方法
一直在努力与类似的东西,但不幸的是你不能这样做.组件模板在运行时编译.所以,基本上,我会创建一个组件来编译其他子组件(我实际上是这样做的)
不推荐使用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) ) } }