Angular 2 stable:templateUrl变量 [英] Angular 2 stable: templateUrl variable

查看:211
本文介绍了Angular 2 stable:templateUrl变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的AngularJS(使用2稳定)。我有一个现有的PHP / Codeigniter3应用程序,我的工作是做一个SPA。

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.

例如:

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


推荐答案

angular2 final 中,它可能如下所示:

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示例

Plunker Example

我想有其他方法做 ngSwitch ngTemplateOutlet

这篇关于Angular 2 stable:templateUrl变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆