2016-09-30 48 views
0

我对AngularJS(使用2个稳定)相当陌生。我有一个现有的PHP/Codeigniter3应用程序,我的工作是制作SPA。我遇到了一个问题,我根本无法访问路由器参数,将它们添加到templateUrl中。Angular 2稳定性:templateUrl变量

例如:

import { Component, OnInit } from '@angular/core'; 
import { Router, ActivatedRoute, Params } from '@angular/router'; 

@Component({ 
    selector: 'apps_container', 
    // template: `You just accessed app: {{app_name}}` // This binding works obviously. 
    templateUrl: (() => { 
    // return 'app/' + this.route.params['app_name'] // Will never work no matter what because I have no access to route 
    return 'app/:app_name'; // Treated as a string. 
    })() 
}) 

export class AppViewComponent { 
    app_name: any; 

    constructor(
    private route: ActivatedRoute, 
    private router: Router 

) {} 

    ngOnInit() { 
    this.route.params.forEach((params: Params) => { 
     this.app_name = params['app_name']; 
    }); 
    } 
} 
+0

'return“app /'”+ app_name +“'”;' – micronyks

+0

@micronyks如果我照你的建议做,我会得到“错误TS2304:找不到名字'app_name'。来自编译器。如果我使用“return”app /'“+ this.app_name +”'“;”我得到一个未定义的变量,这是有道理的,因为构造函数甚至没有初始化。 –

+0

尝试在导出类AppViewComponent中添加'private app_name' –

回答

1

话虽这么说,你可以做到这一点通过动态元件装配。

angular2最终它可能是这样的:

@Component({ 
    selector: 'app-container', 
    template: '<template #vcRef></template>' 
}) 

export class AppContainerComponent { 
    @ViewChild('vcRef', { read: ViewContainerRef }) vcRef: ViewContainerRef; 
    constructor(
    private route: ActivatedRoute, 
    private cmpFactoryResolver: ComponentFactoryResolver, 
    private compiler: Compiler 
) { } 

    ngOnInit() { 
    this.route.params.forEach((params: Params) => { 
     this.loadDynamicComponent(params['app_name']); 
    }); 
    } 

    loadDynamicComponent(appName) { 
    this.vcRef.clear(); 

    @Component({ 
     selector: 'dynamic-comp', 
     templateUrl: `src/templates/${appName}.html` 
    }) 
    class DynamicComponent { }; 

    @NgModule({ 
     imports: [CommonModule], 
     declarations: [DynamicComponent] 
    }) 
    class DynamicModule { } 
    this.compiler.compileModuleAndAllComponentsAsync(DynamicModule) 
     .then(factory => { 
     const compFactory = factory.componentFactories 
      .find(x => x.componentType === DynamicComponent); 
     const cmpRef = this.vcRef.createComponent(compFactory); 
     cmpRef.instance.prop = 'test'; 
     cmpRef.instance.outputChange.subscribe(()=>...);; 
     }); 
    } 
} 

Plunker Example

我想还有其他的方法可以做到像ngSwitchngTemplateOutlet

0

templateUrl回调将是在创建组件之前执行,换句话说在路由注入之前执行,所以在那里有两种方法可以做你想做的事:

  1. 使用window.location来获取当前url并手动解析参数。
  2. 添加路由器侦听器以检测RoutesRecognized事件并使用其state:RouterStateSnapshot属性查找参数并将其保存到模板回调中使用的静态变量。
0

yurzui - 动态添加的组件是否获取父组件中的所有绑定 - AppContainerComponent在您的示例中?