Угловые компоненты предназначены для изоляции друг от друга, поэтому создание такого рода прямой зависимости между компонентами невозможно - вы должны внедрить зависимости.
Итак, одну вещь, которую вы могли бы сделать, это попытаться 'вставить шаблон в другой компонент.Это может работать (не проверенный код):
App.component.html:
<ng-template #template>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right"
aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
This is a modal.
</div>
</ng-template>
<another-component [template]="myModal"></another-component>
App.component.ts:
@ViewChild('template') myModal; // get your template reference in the component
Another.component.ts:
import { Component, OnInit, TemplateRef } from '@angular/core';
export class AnotherComponent implements OnInit {
@Input template: any; // or perhaps of type TemplateRef<any>;
public openModal() {
debugger;
this.appComponent.openModal(this.template);
}
}
Я не совсем уверен, что это сработает, но стоит попробовать.
Однако, возможно, лучшим вариантом является нажатие кнопки в дочернем элементе для открытия модели.Вы запускаете событие, которое app.component затем перехватывает, и оно открывает модальное окно.См. это и это .