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

后端 未结 3 699
孤城傲影
孤城傲影 2021-02-02 15:04

I have a number of angular 1.5 components that all take the same attributes and data structure. I think they could be re-factored into a single component, but I need a way to dy

相关标签:
3条回答
  • 2021-02-02 15:23

    You have to have the switching logic somewhere in any case so why not simply have it in a parent component template?

    Having clean and understandable AngularJS template in that case is IMO more valuable than a bit of repetition:

    <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>
    

    Even if you change the myComponentDef.type on the fly, the components in the switch will correctly call their respective $onDestroy and $onInit methods and load data as expected - no magic, no voodoo.

    0 讨论(0)
  • 2021-02-02 15:42

    You can inject any service and set dynamic url

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

    0 讨论(0)
  • 2021-02-02 15:46

    This is not something that components were specially made for. The task narrows down to using a directive with dynamic templates. The existing one is ng-include.

    To use it within a component, it should be:

    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';
          }
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题