在过go 的几天里,我一直在玩Angular 2,想知道是否有可能为@View装饰师提供动态templateUrl.

我试着给它传递一个函数,然后从中返回一个字符串,但是整个函数变成了一个字符串.

我还没用过Angular 1.所以我不知道我是不是用了错误的方法,但这是可能的,还是有更好的方法来创建动态视图?

例如,如果用户未登录,我可能希望显示一个表单,但如果用户已登录,我可能希望显示一条文本消息.

像这样的东西是行不通的:

@Component({
  selector: 'my-component'
})
@View({
  // This doesn't work
  templateUrl: function() {
    return this.isLoggedIn ? 'logged-in.html' : 'logged-out.html';
  }
})
class MyComponent {
  constructor() {
    this.loggedIn = false;
  }
}

任何帮助都将不胜感激.

推荐答案

虽然可能不是最优雅的解决方案,但我使用DynamicComponentLoader和ElementRef为组件动态分配模板值.事实上,我一直在寻找一种解决方案,可以在占位符中添加多个自定义组件.

我try 了shmck概述的函数中的服务注入,这不起作用,因为调用模板函数时服务还不可用.实际上,this指的是窗口对象.

我使用的解决方案的参考URL位于:create dynamic anchorName/Components with ComponentResolver and ngFor in Angular2

我也是这样参考Plnkr1Plnkr2的.

site Dartdocs提供了Angular 2 DynamicComponentLoader类的优秀文档,也适用于TypeScript.

简而言之:

一个简单的组件作为要使用的模板

@Component({
  selector: 'dt2-simple-block',
  properties: ["idx"],
  template: `<h1>Simple block for  {{ idx }} </h1>`,
  directives: []
})
class dt2SimpleBlock {
  constructor() {
  }
}

包含要添加的所有组件的组件的构造函数(我的应用程序需要包含多个Child:

 constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {

  //iterate
  for (var i = 0; i < toSomething; i++) {
      // build the template
      var blockdirective = 'dt2-simple-block'
      var template = '<' + blockdirective + 
                     ' idx="' + this.userBlocks.userHomePanelBlocks[i] +
                     '"></' + blockdirective + '>';
      console.log(template);   // debugging purpose
      var directives = [dt2SimpleBlock];
        loader.loadNextToLocation(toComponent(template, directives), elementRef);
    }

以及要放在某个位置作为实用程序的帮助器函数

function toComponent(template, directives = []) {
  @Component({ selector: 'fake-component' })
  @View({ template, directives })
  class FakeComponent { }

  return FakeComponent;
}

Angular相关问答推荐

有没有一种方法用timeout()操作符创建计数器,用于超时一个观察对象?

在不使用散列(#)路由的情况下刷新Angular 8的SPA时,删除404错误

身份验证卫士给了我17个Angular 的任何类型

如何在init为FALSE时以Angular 初始化主拇指擦除器-Swiper 11.0.6Angular 17 SSR

如何重新显示ngbAlert(Bootstrap widgest for Angular)消息后再次驳回它

确保我的角库S服务构建提供独立的友好提供功能

如何确保[共享]组件是真正的哑组件?(Angular )

Angular :为什么我得到了一个可观察到的共鸣

使用`UrlHandlingStrategy`更改位置

ngrx 效果等到从初始值以外的其他状态收到响应

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

单选按钮的Angular2 Reactive Forms formControl

怎样在 Angular 2 或 4 中将输入字段设为只读?

使用 NPM 安装 Font Awesome 5

可从 Angular2 中的

使用directive指令将类添加到host元素中

如何处理解析器中的错误

在 Angular 2 中使用 store (ngrx) 有什么好处

Angular 5 和material - 如何从 SnackBar 组件更改背景 colored颜色