[英]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. 在角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";
}
}
}
My question is how to implement the same function in below Angular 2 component? 我的问题是如何在Angular 2组件下面实现相同的功能?
@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 请参阅Angular 2:如何动态添加和删除组件
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";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.