Sherief Alaa Sherief Alaa - 1 month ago 19
PHP Question

Angular 2 stable: templateUrl variable

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'];
});
}
}

Answer

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(()=>...);;
      });
  }
}

Plunker Example

I guess there are other ways to do that like ngSwitch or ngTemplateOutlet