我对AngularJS相当新(使用2稳定版)。我有一个现有的PHP / Codeigniter3应用程序,我的工作是制作SPA。我遇到了一个问题,我根本无法访问路由器参数将它们添加到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 :(得分:1)
话虽如此,你可以通过动态组件加载来做到这一点。
在 angular2 final 中,它可能如下所示:
@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 强>
我想还有其他方法可以做到ngSwitch
或ngTemplateOutlet
答案 1 :(得分:0)
可以在此处找到与您的问题相关的几个有趣的答案:Dynamic template in templatURL in angular2
答案 2 :(得分:0)
templateUrl
回调将在创建组件之前执行,换句话说就是在路由注入之前执行,因此有两种方法可以执行您想要的操作:
window.location
获取当前网址并手动解析参数。RoutesRecognized
事件并使用其state:RouterStateSnapshot
属性查找参数并将其保存到静态变量以用于模板回调。答案 3 :(得分:0)
yurzui - 动态添加的组件是否获取父组件中的所有绑定 - 示例中的AppContainerComponent?