简体   繁体   English

Angular 2中的动态模板URL

[英]Dynamic template URL in Angular 2

I have two different sidebar, and I want from a variable that I get back from the url, switch between two templateURL. 我有两个不同的侧边栏,我想从从URL返回的变量中,在两个templateURL之间切换。

@Component({
    selector: 'sidebar',
    templateUrl: './sidebar.component.html',
    styleUrls: [
        './sidebar.component.css'
    ]
})

I did this but i have a message erreur: 我这样做了,但是我收到一条消息erreur:

import {
  Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
  ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';
@Component({
    selector: 'sidebar',
    templateUrl: '<ng-container #dynamicTemplate></ng-container>',
    styleUrls: [
        './sidebar.component.css'
    ]
})

export class SidebarComponent implements OnInit {
@ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;
constructor(
private _compiler: Compiler,
        private _injector: Injector,
        private _m: NgModuleRef<any>
) {}
ngAfterViewInit() {
        let myTemplateUrl = './sidebar.component.html';

        if (this.modee === 'char') {
            myTemplateUrl = './Othersidebar.component.html';
        }
        const tmpCmp = Component({
            moduleId: module.id, templateUrl: myTemplateUrl
        })(class {
        });
        const tmpModule = NgModule({declarations: [tmpCmp]})(class {
        });

        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
            .then((factories) => {
                const f = factories.componentFactories[0];
                const cmpRef = f.create(this._injector, [], null, this._m);
                cmpRef.instance.name = 'dynamic';
                this.dynamicTemplate.insert(cmpRef.hostView);
            });
    }

and thes is the error message : 和是错误消息:

client?afea:119 ..../app/sidebar.component.ts
Module not found: Error: Can't resolve './<ng-container #dynamicTemplate></ng-container>' in '.....\app\sidebar'
 @ ./src/main/webapp/app/layouts/sidebar/sidebar.component.ts 303:18-77
 @ ./src/main/webapp/app/layouts/index.ts
 @ ./src/main/webapp/app/app.module.ts
 @ ./src/main/webapp/app/app.main.ts
 @ multi (webpack)-dev-server/client?http://localhost:9060 webpack/hot/dev-server ./src/main/webapp/app/app.main

is there a solution to that? 有解决方案吗? and what is this error? 这是什么错误? thx 谢谢

i find a solution : 我找到一个解决方案:

templateUrl: '<ng-container #dynamicTemplate></ng-container>',

change temlateURL to template 将temlateURL更改为模板

but he dos not work 但他不工作

Why not have a router guard with the sidebar template, and then switching based on route or URL. 为什么不准备带有侧边栏模板的路由器防护,然后根据路由或URL进行切换。 Sidebar Module with 2 different sidebars, and 2 routes for that module. 具有2个不同侧边栏和该模块2条路径的侧边栏模块。 Template1, Tempalte2. 模板1,Tempalte2。

Just my 2 cents. 只是我的2美分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM