0

我需要在正文位于 app.component.html 上的不同页面上显示模式弹出窗口。

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">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        This is a modal.
      </div>
    </ng-template>

App.component.ts:

   import { TemplateRef } from '@angular/core';
   public openModal(template: TemplateRef<any>) {
        debugger;
        this.modalRef = this.modalService.show(template); // {3}
      }

另一个.component.html:

 <input type="button" class="btn" (click)="openModal(template)" value="open popup" />

另一个.component.ts:

import { Component, OnInit, TemplateRef } from '@angular/core';
 export class ABC implements OnInit {
  template: TemplateRef<any>;
  public openModal(template) {
    debugger;  // getting null as template
    this.appComponent.openModal(template);
  }
 }
4

1 回答 1

0

Angular 组件旨在相互隔离,因此不可能在组件之间创建这种直接依赖关系——您必须注入依赖关系。

因此,您可以做的一件事是尝试将模板“注入”到另一个组件中。这可能有效(未测试代码):

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">&times;</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

另一个.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 然后捕获的事件,并打开模式。看到这个这个

于 2018-06-12T14:03:54.053 回答