基于数据的不同ChildComponent

Different ChildComponent based on data

如何根据从数据库中获取的数据更改组件?
我正在使用这样的东西:stackblitz
但是工具是根据用户角色显示的。 (数据库returns哪些工具,命令 等等)

我可以想到两种方法:

第一
使用 *ngIf 如:

<div class="tools-wrapper controls">
  <div class="tools-container">
    <app-tool-menu *ngIf="existsInData('menu')"></app-tool-menu>
    <mat-divider *ngIf="existsInData('menu')"></mat-divider>
    <app-tool-refresh *ngIf="existsInData('refresh')"></app-tool-refresh>
    <app-tool-info *ngIf="existsInData('info')"></app-tool-info>
    <app-tool-edit *ngIf="existsInData('edit')"></app-tool-edit>
  </div>
</div>

这不够动态。

第二个 使用 factoryResolver

@Injectable()
export class InjectorService {
  constructor(private factoryResolver: ComponentFactoryResolver) { }

  setRootViewContainerRef(viewContainerRef) {
    this.rootViewContainer = viewContainerRef;
  }

  addDynamicComponents(data: any[]) {
    const component = factory.create(this.rootViewContainer.parentInjector);

    data.forEach((tool) => {
      const toolComponent = this.toolMapping(tool);
      const factory = this.factoryResolver.resolveComponentFactory(toolComponent);
      this.rootViewContainer.insert(component.hostView);
    });
  }

  toolMapping(tool) {
    const tools = {
      'menu': MenuComponent,
      'refresh': RefreshComponent,
      'info': InfoComponent,
      'edit': EditComponent,
    };
    return tools[tool];
  }
}



@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1> 
    <ng-template #dynamic></ng-template>
  `
})
export class AppComponent implements OnInit {
  name = 'from Angular';

  @ViewChild('dynamic', { read: ViewContainerRef }) 
  viewContainerRef: ViewContainerRef;

  constructor(private service: InjectorService ) {}

  ngOnInit() {
    this.service.setRootViewContainerRef(this.viewContainerRef);
    this.service.addDynamicComponents(.. data ..);
  }
}

嗯,这段代码中有很多开销,比如为我拥有的每个类似构造定义一个工具映射或创建一个服务。

是否有更好更清洁的解决方案?

数据如下(可根据需要修改):

[
  {type: 'menu', tooltip: '', ...},
  {type: 'divider', tooltip: '',...},
  {type: 'refresh', tooltip: '', ...},
  {type: 'info', tooltip: '',...},
  {type: 'edit', tooltip: '',...},
]

如何将 <ng-container>ngComponentOutlet 一起使用?它比 ComponentFactoryResolver 解决方案要简洁得多。

import { Component } from '@angular/core';

import { AComponent } from './a.component';
import { BComponent } from './b.component';
import { CComponent } from './c.component';

@Component({
  selector: 'my-app',
  template: `
    <input type="radio" value="A" name="comp" [(ngModel)]="radioValue"> A
    <input type="radio" value="B" name="comp" [(ngModel)]="radioValue"> B
    <input type="radio" value="C" name="comp" [(ngModel)]="radioValue"> C

    <ng-container [ngComponentOutlet]="selected"></ng-container>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  radioValue: 'A' | 'B' | 'C';

  get selected() {
    switch (this.radioValue) {
      case 'A': {
        return AComponent
      }
      case 'B': {
        return BComponent
      }
      case 'C': {
        return CComponent
      }
    }
  }
}

Live demo

AngularJS 中可以仅通过组件标签编译组件,例如: <comp></comp> 如果它以字符串形式出现。

但在新 Angular 不幸的是还没有。我看了 ComponentFactoryResolverngComponentOutlet API 的。他们只接受 Type<T> resolveComponentFactory ,其中 T 是一些 Component/Directive... class。

因此您不能将组件选择器作为字符串传递。

作为解决方案类型:

  • 创建 Map<string, any>()key - 类型,any - 组件类型

    并在模板中迭代数据:

    <ng-container  *ngFor="let itm of data">
        <ng-container *ngComponentOutlet="someMap.get(itm.type)"> 
        </ng-container>
    </ng-container> 
    
  • 创建方法getComponentType(type: string)。这里有一些搜索逻辑。 模板:

    <ng-container *ngFor="let itm of data">
        <ng-container *ngComponentOutlet="getComponentType(itm.type)">
        </ng-container>
    </ng-container>