I am fairly new to AngularJS (using 2 stable). I have an existing PHP/Codeigniter3 app and my job is to make an SPA. I am running into a problem where I can't access router params at all to add them in a templateUrl.
For example:
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'];
});
}
}
That being said, you could to do that via dynamic component loading.
In angular2 final it might look like this:
@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(()=>...);;
});
}
}
I guess there are other ways to do that like ngSwitch
or ngTemplateOutlet
Severals interresting answers related to your question can be found here : Dynamic template in templatURL in angular2
templateUrl
callback will be executed before creating component, in other words before route injection, so there are two ways to do what you want:
window.location
to get current url and manually parse parameters.RoutesRecognized
event and use its state:RouterStateSnapshot
property to find parameters and save it to static variable to use in template callback.yurzui - does the dynamically added component gets all the binding in the parent component - AppContainerComponent in your example?