templatURL中的动态模板,角度为2

bin*_*dMe 15 javascript angular

每当我必须在页面中动态包含一个模板时,我一直在使用角度1中的ng-include.

现在如何在角度2中实现这一点.我试过搜索并找到了这些:

https://groups.google.com/forum/#!topic/angular/ROkKDHboWoA,

https://github.com/angular/angular/issues/2753

有人可以解释如何在angular2中执行此操作,因为链接说由于某些安全原因不包括ng-include.

或至少如何在templateUrl属性中使用可验证的值,以便可以在服务器端处理可验证值以提供模板...

S.K*_*ski 11

正如你在本期 Angular repo中看到的那样,很可能我们不会得到那个指令.我们是否需要这个指令已经进行了长时间的讨论,如果没有提供我们如何通过自己实现它.

我试图给出一个如何实现它的简单例子.

@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 ;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于演示检查这个Plunker.