Angular2根据全局设置为路径加载不同的组件

时间:2017-08-11 08:13:25

标签: angular angular2-routing

我们有一个要求,取决于静态/全局设置,根据客户需要为路径加载不同的组件。原因是他们希望应用程序的一部分具有稍微不同的功能,因此我们将为每个应用程序编写一个组件来满足他们的场景。有没有办法动态地/在运行时为路径选择组件并保持相同的路由/ URL。以下是我们希望实现的简化示例:

的Component1:

@Component({
  selector: 'customeronecomponent',
  templateUrl: './customeronecomponent.component.html'
})

export class CustomerOneComponent implements OnInit {
}

COMPONENT2:

@Component({
  selector: 'customertwocomponent',
  templateUrl: './customertwocomponent.component.html'
})

export class CustomerTwoComponent implements OnInit {
}

路线:

{ path: 'home', component: CustomerComponentProvider },

在这种情况下,CustomerComponentProvider将在内部检查设置,并返回CustomerOneComponent或CustomerTwoComponent。

在angular2 / 4中,这是最好的方法,或者最好是单个组件并在该组件上加载正确的组件,我看到的缺点是每个路由我们将有三个组件而不是两个组件我们需要这个。

4 个答案:

答案 0 :(得分:5)

您可能已在CustomerComponentProvider中内部执行此操作,但如果不是 - 则有Dynamic Component Loader

文档中给出的示例有点忙,所以这里是一个愚蠢的版本:Plunker

本质上,包装器用于根据传入的配置字符串或从服务检索的组件之间进行切换。

import { Component, Input, OnChanges, 
  ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { Component1 } from './component1';
import { Component2 } from './component2';

@Component({
  selector: 'component-wrapper',
  template: `<div></div>`
})
export class ComponentWrapper implements OnChanges {

  @Input() config;

  private componentMap = {
    component1 : Component1,
    component2 : Component2,
  }

  constructor(
    private viewContainerRef: ViewContainerRef,
    private componentFactoryResolver: ComponentFactoryResolver
  ) {}

  ngOnChanges() { 
    this.setComponent();
  }

  setComponent() {
    const componentFactory = this.componentFactoryResolver
      .resolveComponentFactory(this.componentMap[this.config]);
    this.viewContainerRef.clear();
    this.viewContainerRef.createComponent(componentFactory);
  }

}

答案 1 :(得分:1)

在CustomerComponentProvider的模板中,您可以通过检查设置

来显示任一组件

假设您的设置返回客户类型(1/2),您可以根据该类型将showCustomerOne / showCustomerTwo设置为true

<app-customer-one-component *ngIf="showCustomerOne"> </app-customer-one-component>
<app-customer-two-component *ngIf="showCustomerTwo"> </app-customer-two-component>

检查CustomComponentProvider构造函数中的设置,并将showCustomerOne设置为True或将showCustomerTwo设置为True。

  showCustomerOne;
  showCustomerTwo;

  constructor() {
     if(customer.type == '1'){
         this.showCustomerOne = true;
      }else if (customer.type == '2'){
         this.showCustomerTwo = true;
      }
  };

答案 2 :(得分:0)

您可以随时更新路由器配置,因此根据您的设置,您可以添加或更新路由配置以解析您需要的组件。

在路由器上查看config property或更适合此问题的resetConfig方法。您可以在要处理此问题的组件中注入Router,并根据您拥有的全局设置更新路由。

答案 3 :(得分:0)

您可以尝试reflect-metadata

之类的内容

您可以为类型定义元数据键,然后根据配置中的内容获取组件的类型并将其输入routeConfig或通过router.resetConfig重置路由器为@Adrian Faciu提示:

https://angular.io/api/router/Router#resetConfig

相关问题