2017-09-14 176 views
1

In Angular 1,我們可以使用templateUrl來動態加載不同的外部模板,如下所示。如何在Angular 2組件中動態加載外部模板?

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

我的問題是如何實現下角2成分相同的功能?

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

的https: //stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template-to-compile-dynamic-component-with -angular –

+0

可能的重複[如何使用/創建動態模板來編譯動態組件與Angular 2.0?](https://stackoverflow.com/questions/38888008/how-can-i-use-create-dynamic-template -to-compile-dynamic-component-with-angular) –

回答

1

如果要加載組件動態然後

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

Angular 2: How to Dynamically Add & remove Components

如果你想只改變模板的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"; 
     }  
    } 
} 
+0

感謝您的回覆,實際上我使用Webpack來打包模板文件,對於第二種方式,我們是否應該使用template:require('{{tmplUrl}}'')替換templateUrl:「{{tmplUrl}}」 –

+0

是的,這應該工作 –

相關問題