有没有办法为 angular 1.5 组件动态呈现不同的模板

Is there a way to dynamically render different templates for an angular 1.5 component

我有许多 angular 1.5 组件,它们都具有相同的属性和数据结构。我认为它们可以重构为单个组件,但我需要一种方法来根据 type 属性的内插值动态选择模板。

var myComponentDef = {
    bindings: {
        type: '<'
    },
    templateUrl: // This should be dynamic based on interpolated type value
};

angular.module('myModule').component('myComponent', myComponentDef);

我不能使用 templateUrl function($element, $attrs) {},因为 $attrs 中的值是未插值的,所以我无法获得传入数据中指定的类型。

我可以只有一个包含一系列 ng-ifng-switch 指令的大模板,但我想将模板分开。

或者,我可以将组件分开并在父组件中使用 ng-switch 等,但我不喜欢这样,因为它看起来重复很多。

我正在寻找一种解决方案,我可以在其中使用传递到绑定中的内插 type 来匹配每种类型的模板 url,然后用于构建组件。

这可能吗?

谢谢

这不是专门为之制作的组件。该任务缩小到使用带有动态模板的指令。现有的是ng-include.

要在组件中使用它,应该是:

var myComponentDef = {
  bindings: {
    type: '<'
  },
  template: '<div ng-include="$ctrl.templateUrl">',
  controller: function () {
    this.$onChanges = (changes) => {
      if (changes.type && this.type) {
        this.templateUrl = this.type + '.html';
      }
    }
  }
}

您可以注入任何服务并设置动态url

angular.module('myApp').component("dynamicTempate", {
        controller: yourController,
        templateUrl: ['$routeParams', function (routeParams) {
           
            return 'app/' + routeParams["yourParam"] + ".html";
        
        }],
        bindings: {
        },
        require: {
        }
    });

在任何情况下你都必须在某个地方有切换逻辑,那么为什么不简单地把它放在父组件模板中呢?

在这种情况下,拥有简洁易懂的 AngularJS 模板在我看来比一些重复更有价值:

<ng-container ng-switch="$ctrl.myComponentDef.type">
  <component-type1 ng-switch-when="type1" param="$ctrl.myComponentDef"></component-type1>
  <component-type2 ng-switch-when="type2" param="$ctrl.myComponentDef"></component-type2>
</ng-container>

即使您即时更改 myComponentDef.type,开关中的组件也会正确调用它们各自的 $onDestroy$onInit 方法并按预期加载数据 - 没有魔法,没有巫术。