大佬教程收集整理的这篇文章主要介绍了如何为Angular2 Component提供动态templateUrl?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
但是没有能力访问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) ) } }
以上是大佬教程为你收集整理的如何为Angular2 Component提供动态templateUrl?全部内容,希望文章能够帮你解决如何为Angular2 Component提供动态templateUrl?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。