如何在Angular 2 Component中动态加载外部模板? [英] How to dynamically load external template in Angular 2 Component?
本文介绍了如何在Angular 2 Component中动态加载外部模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Angular 1 中,我们可以使用 templateUrl 来动态加载不同的外部模板,如下所示.
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";
}
}
}
我的问题是如何在 Angular 2 组件下面实现相同的功能?
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);
}
如果您只想更改模板网址,请尝试如下操作:
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";
}
}
}
这篇关于如何在Angular 2 Component中动态加载外部模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文