如何动态显示另一个内部的组件?

How to show component inside another dynamically?

我有一个组件LayersComponent

@Component({
  selector: "app-layers",
  templateUrl: "./layers.component.html",
  styleUrls: ["./layers.component.sass"]
})
export class LayersComponent implements OnInit {
}

模板是:

<div class="Layers">
  Text

  <!-- Create component below -->
  <app-another-component></app-another-component>
</div>

我想在当前组件中创建并显示动态组件 <app-another-component></app-another-component>

但我需要从另一个不在 LayersComponent 内的组件创建命令,而是从应用程序中的另一个组件发送命令。

怎么做?

我试过:

<div class="Layers">
   Text
   <ng-container *ngTemplateOutlet="app-another-component"></ng-container>
</div>

但是我不知道如何向外发送命令LayersComponent?

注入HTML内容的简单情况的解决方案是使用<ng-content>

parent

<child>
  <p>Some injected HTML content</p>
</child>

child

<p>
  <!-- inner HTML of <child> will go here -->
  <ng-content></ng-content>
</p>

ngTemplateOutlet

如果你想动态注入HTML,你只需在<child>中动态声明HTML:

parent

<child>
  <p *ngIf="condition1">Some conditional injected HTML content</p>
  <p *ngIf="condition2">Some different conditional injected HTML content</p>
</child>

如果要引用命名模板,您将使用 ngTemplateOutlet

parent

<child>
   <ng-container *ngTemplateOutlet="body"></ng-container>
</child>

<ng-template #body>
  <p>Some reusable content</p>
</ng-template>

目标注入HTML

要定位注入的特定部分 HTML,请使用选择器:

parent

<child>
  <span heading>TITLE</span>
  <p body>The body</p>
</child>

child

<h1><ng-content select="[heading]"></ng-content></h1>
<div select="[body]">

</div>

使用 Angular 中的 ComponentFactoryResolver 来处理多个组件的动态加载器:

示例代码如下:

import {
    Component,
    ComponentFactory,
    ComponentRef,
    ComponentFactoryResolver,
    ViewContainerRef,
    ViewChild
} from '@angular/core'
import { AComponent } from './a.component';
import { BComponent } from './b.component';

@Component({
    selector: 'modal-resolver',
    template: `
        <template #modalContainer></template>
    `,
})
export class ModalResolver {
    @ViewChild("modalContainer", { read: ViewContainerRef }) container;
    @Input() name;
    componentRef: ComponentRef;

    listComponent: {
        'modalA': AComponent,
        'modalB': BComponent
    }

    constructor(private resolver: ComponentFactoryResolver) { }

    ngOnInit() {
        this.loadComponent(this.name);
    }
    loadComponent(type) {
        this.container.clear();
        const factory: ComponentFactory = this.resolver.resolveComponentFactory(this.listComponent[this.name]);

        this.componentRef = this.container.createComponent(factory);

        this.componentRef.instance.type = type;

        this.componentRef.instance.output.subscribe(event => console.log(event));

    }

    ngOnDestroy() {
        this.componentRef.destroy();
    }
}

那你就用它:

<modal-resolver name="modalA"></modal-resolver>

您可以从 Angular 文档中阅读更多内容: https://angular.io/guide/dynamic-component-loader