5

In Angular 1, we can use templateUrl to load different external templates dynamically as below.

angular.module('testmodule).diretive('testDirective'), function(){
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      data: '@',
    },
    templateUrl: function(element, attrs) {
       if(attrs.hasOwnProperty("attr")){
          return "views/test1.html";
       } else {
         return "views/test2.html"; 
       }                    
   }
}

My question is how to implement the same function in below Angular 2 component?

@Component({
  selector: 'testDirective, [testDirective]',
  template: require('./views/test1.html') or require ('./views/test2.html')
})
export class Angular2Component {
   ...
}
Leo Sun
  • 51
  • 1
  • 3
  • 2
    https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with-angular – Günter Zöchbauer Sep 14 '17 at 12:03
  • Possible duplicate of [How can I use/create dynamic template to compile dynamic Component with Angular 2.0?](https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with-angular) – The Hungry Dictator Sep 14 '17 at 12:09

1 Answers1

2

If you want to load component dynamically then

@ViewChild('container', { read: ViewContainerRef })    container: ViewContainerRef; 
addComponent(){      
  var comp = this._cfr.resolveComponentFactory(ExpComponent);
  var expComponent = this.container.createComponent(comp);
}

See Angular 2: How to Dynamically Add & remove Components

If you want to change only the template url then try like this:

@Component({
  selector: 'app-simple-component',
  templateUrl: "{{tmplUrl}}"
})
class SomeComponent {
  tmplUrl: string= 'views/test1.html';
  constructor() {
       if(attrs.hasOwnProperty("attr")){
          this.tmplUrl ="views/test1.html";
       } else {
         this.tmplUrl ="views/test2.html"; 
       }    
  }
}
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
  • thanks for your reply, actually I use Webpack to package the template file, for the second way, shall we use template: require('{{tmplUrl}}'') to replace templateUrl: "{{tmplUrl}}" – Leo Sun Sep 15 '17 at 03:57