每当我必须在页面中动态包含模板时,我就一直在 Angular 1 中使用 ng-include 。
现在如何在 Angular 2 中实现这一点。我尝试搜索并找到了这些:
https://groups.google.com/forum/#!topic/angular/ROkKDHboWoA https://groups.google.com/forum/#!topic/angular/ROkKDHboWoA ,
https://github.com/angular/angular/issues/2753 https://github.com/angular/angular/issues/2753
有人可以解释如何在 Angular2 中执行此操作,因为链接显示由于某些安全原因未包含 ng-include 。
或者至少如何在 templateUrl 属性中使用变量,以便可以在服务器端处理变量值以服务模板......
正如你所看到的issue https://github.com/angular/angular/issues/2753在 Angular 仓库中,我们很可能不会收到该指令。我们是否需要这个指令,以及如果没有提供我们如何自己实施它,已经进行了很长时间的讨论。
我试图举一个简单的例子来说明如何实现它。
@Component({
selector: 'my-ng-include',
template: '<div #myNgIncludeContent></div>'
})
export class MyNgInclude implements OnInit {
@Input('src')
private templateUrl: string;
@ViewChild('myNgIncludeContent', { read: ViewContainerRef })
protected contentTarget: ViewContainerRef;
constructor(private componentResolver: ComponentResolver) {}
ngOnInit() {
var dynamicComponent = this.createContentComponent(this.templateUrl);
this.componentResolver.resolveComponent(dynamicComponent)
.then((factory: any) => this.contentTarget.createComponent(factory));
}
createContentComponent(templateUrl) {
@Component({
selector: 'my-ng-include-content',
templateUrl: templateUrl,
directives: FORM_DIRECTIVES,
})
class MyNgIncludeContent {}
return MyNgIncludeContent ;
}
}
对于演示,请检查此Plunker http://plnkr.co/edit/OjxKE9HWnDInKojuhhk8?p=preview.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)