加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何为Angular2 Component提供动态templateUrl?

发布时间:2020-12-17 17:16:07 所属栏目:安全 来源:网络整理
导读:我想根据从父组件传递的值加载组件templateUrl.我知道可以通过@Input通过属性绑定到组件,我在下面举例说明my Html将作为templateName传递. 但是没有能力访问templateUrl函数中的@Input值.我认为templateUrl是第一个通过询问HTML来评估的东西,之后所有其他组
我想根据从父组件传递的值加载组件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) )
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读