如何在Angular 2组件中动态加载外部模板?

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

2
https://dev59.com/cFkT5IYBdhLWcg3wPdGU - Günter Zöchbauer
1个回答

2

如果您想动态加载组件,则需要

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

请查看Angular 2:如何动态添加和删除组件

如果您只想更改模板URL,请尝试以下方式:

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

谢谢您的回复,实际上我使用Webpack来打包模板文件。对于第二种方法,我们可以使用template: require('{{tmplUrl}}'')来替换templateUrl: "{{tmplUrl}}"吗? - Leo Sun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接