微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – ng2-bootstrap,调用来自父compnt的子组件中定义的模态

我使用 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已定义并且它在其子组件中.

解决方法

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

ChildComponent

@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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐