Как показать компонент внутри другого динамически? - PullRequest
0 голосов
/ 17 февраля 2020

У меня есть компонент 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> внутри текущего компонента.

Но мне нужно отправить команду create из другого компонента не внутри LayersComponent, а где-то из другого компонента в приложении.

Как это сделать?

Я пытался:

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

Но я не знаю, как отправить команду за пределы LayersComponent?

Ответы [ 2 ]

1 голос
/ 17 февраля 2020

Использование ComponentFactoryResolver в Angular для обработки динамического загрузчика c для нескольких компонентов:

Вот пример кода:

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

1 голос
/ 17 февраля 2020

Решением для простого случая введения 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, вы просто динамически объявляете HTML внутри <child>:

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

Чтобы нацелиться на определенные c части введенного HTML, используйте селекторы:

parent

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

ребенок

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

</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...