我想有一个Modal提示用户删除一条记录,我想在不同记录类型的多个组件中重复使用它.
ngBootstrap站点显示“组件为内容”示例,但在该示例中,看起来ModalComponent指示是打开还是关闭ModalContents.我希望能够从另一个(任意)组件打开/关闭模态的实例.
这可能吗?
import { NgModule} from '@angular/core'; import { CommonModalComponent } from './modal.component'; import { ModalDirective,ModalModule } from 'ng2-bootstrap/ng2-bootstrap'; @NgModule({ imports:[ModalModule],declarations: [ CommonModalComponent ],exports:[CommonModalComponent] }) export class CommonModule {}
>如您所见,CommonModalComponent是一个声明
CommonModule,创建如下组件,
import {Component,Input,ViewChild} from '@angular/core'; import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ selector: 'common-modal',template: ` <div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">{{title}}</h4> <button type="button" class="close pull-right" aria-label="Close" (click)="hideChildModal()"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <ng-content select=".modal-body"> </ng-content> </div> <div class="modal-footer"> <div class="pull-left"> <button class="btn btn-default" (click)="hide()"> Cancel </button> </div> </div> </div> </div> </div> `,}) export class CommonModalComponent { @ViewChild('childModal') public childModal:ModalDirective; @Input() title?:string; constructor() { } show(){ this.childModal.show(); } hide(){ this.childModal.hide(); } }
>使用AppModule中的CommonModule及其组件,ViewChild,ViewContainerRef,NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {CommonModule} from './common.module'; import {CommonModalComponent} './modal.component'; @Component({ selector: 'my-app',template: ` <div> <h2>Hello {{name}}</h2> <button type="button" class="btn btn-primary" (click)="childModal.show()">Open modal</button> <common-modal #childModal [title]="'common modal'"> </common-modal> </div> `,}) export class App { @ViewChild('childComponent') childComponent:CommonModalComponent; name:string; constructor(private viewContainerRef: ViewContainerRef) { this.name = 'Angular 2 Common Module with ModalComponent' } } @NgModule({ imports: [ BrowserModule,CommonModule ],declarations: [ App ],bootstrap: [ App ] }) export class AppModule {}
附加信息:
>这个通用模块可以用于任何重现您需求的地方
在Angular 2中的ContentProjection的帮助下可以看到
在线以下
<ng-content select=".modal-body"> </ng-content>
>在AppComponent中,您可以使用此项并将项目添加到您的
CommonModal为,
<div class="modal-body"> Some Form Controls or Displaying content </div>
这可以在LIVE DEMO中看到>因为,你想要模态警告信息或确认重用common-modal并创建另一个WarningModalComponent并跨应用程序使用它