javascript - ng2-bootstrap,从父组件调用子组件中定义的Modal

标签 javascript typescript angular bootstrap-modal ng2-bootstrap

我正在使用 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)="lgModal.show()",我也希望能够让父组件访问它并打开模式。

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

那么,如何让父组件知道 lgModal 已定义,并且在其子组件中。

最佳答案

您的解决方案可能如下所示:

子组件

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

父组件

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

另请在此处查看完整示例 https://plnkr.co/edit/2UAB7lpqqAvchTsLwzr6?p=preview

关于javascript - ng2-bootstrap,从父组件调用子组件中定义的Modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37888361/

相关文章:

javascript - 选择一个以特定 div 内的内容结尾的 id

typescript - 如何将匹配的属性从一个对象复制到另一个对象

css - 基于 Angular 中的按钮单击执行不同的动画

javascript - 在新选项卡中打开 PDF,保存文件时给出错误的文件名

angular - 如何修复 npm 审计漏洞 angular 12.0.3

javascript - 如何使用 Chart.js 在标签中放置新行?

php - 如何使用CKEditor作为表单输入?

javascript - 如何发送带有动态 html 内容的电子邮件?

javascript - 类型 'data' 上不存在属性 '() => DocumentData'

javascript - Angular 2 : Contenteditable div doesn't work as expected