簡體   English   中英

如何在Angular 2組件中動態加載外部模板?

[英]How to dynamically load external template in Angular 2 Component?

角1,我們可以使用templateUrl到如下動態地加載不同的外部模板。

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

我的問題是如何在Angular 2組件下面實現相同的功能?

@Component({
  selector: 'testDirective, [testDirective]',
  template: require('./views/test1.html') or require ('./views/test2.html')
})
export class Angular2Component {
   ...
}

如果要動態加載組件

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

請參閱Angular 2:如何動態添加和刪除組件

如果您只想更改模板網址,請嘗試這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM