简体   繁体   中英

How to dynamically load external template in Angular 2 Component?

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 {
   ...
}

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"; 
       }    
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM