ng2-bootstrap,呼叫模态在子comment中定义的子组件中定义的模态



我正在使用ng2-bootstrap用于模态的东西。

我试图将我的模式和其他组件分开。因此,我有以下文件:

addplaylist.modal.ts

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

import {MODAL_DIRECTVES, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
  selector: 'addplaylist-modal',
  directives: [MODAL_DIRECTVES, CORE_DIRECTIVES],
  viewProviders: [BS_VIEW_PROVIDERS],
  templateUrl: 'app/channel/modals/addPlaylistModal.html'
})
export class AddPlaylistModalComponent {
  constructor() {
    console.log(this);
  }
}

addplaylistmodal.html

<div bsModal #lgModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Large modal</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
    </div>
  </div>
</div>

在它的是父组件的html中,我有这样的代码:

  <a (click)="lgModal.show()"><span class="bigplus pull-right"></span></a>
   //some other code
  <addplaylist-modal></addplaylist-modal>

这是父组件: channel.component.ts

import { AddPlaylistModalComponent } from './shared/addPlaylist.modal';
@Component({
  selector: 'channel',
  styleUrls: ['app/channel/channel.css'],
  directives: [PlatformsComponent, PagesComponent, PlaylistComponent, VideosComponent, AddPlaylistModalComponent],
  providers: [PlatformService],
  templateUrl: 'app/channel/channel.html'
})

我想做的,我希望能够让父构成访问它并打开模态,即使我编写(click)=&quot" lgmodal.show()在父组件中。

现在,如果我单击<a (click)="lgModal.show()"><span class="bigplus pull-right"></span></a>,它将说"无法读取未定义的属性展示"

因此,如何让父组件知道lgmodal已定义,并且在其子部件中。

您的解决方案可能看起来像这样:

ChildComponent

@Component({
  ...
  exportAs: 'child'  <== add this line
})
export class AddPlaylistModalComponent {
  @ViewChild('lgModal') lgModal; <== reference to Modal directive
  show(){   <== public method
    this.lgModal.show(); 
  }
}

parentcomponent

template: `<a class="btn btn-success" (click)="c.show()">Add</a>
           <addplaylist-modal #c="child"></addplaylist-modal>`

另请参见https://plnkr.co/edit/2uab7lpqqqavchtslwzr6?p=Preview

最新更新