angular6使用ngx-bootstrap/modal

首先下载ngx-bootstrap:npm install ngx-bootstrap --save

下载后,在module.ts中导入ngx-bootstrap/modal类:

import { ModalModule } from 'ngx-bootstrap';

  imports: [
    ...
    ModelModule,
    ModalModule.forRoot()

]

在组件中,添加按钮,按钮点击后弹出子窗体,其中显示的是一个组件:

组件中实现:

import { Component, OnInit, TemplateRef  } from '@angular/core';

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

  在组件构造函数中注入Modal服务:

  constructor(private http: Http, private modalService: BsModalService) {
  }

bsModalRef: BsModalRef;//弹出的子模块的引用
  openModalWithComponent() {//按钮的click执行函数,打开一个子模块
    //给子组件的成员赋值,如果子组件中含有list、title同名成员,则自动进行了赋值
    const initialState = {
      list: [
        'Open a modal with component',
        'Pass your data',
        'Do something else',
        '...'
      ],
      title: '测试子组件'
    };
    this.bsModalRef = this.modalService.show(DetailComponent, { initialState });//显示子组件
    this.modalService.onHidden.subscribe((r: string) => {//子组件关闭后,触发的订阅函数
      if (this.bsModalRef.content.isCancel)//this.bsModalRef.content代表子组件对象,isCancel是子组件中的一个成员,可以直接访问
        console.log("取消了" + this.bsModalRef.content.value);//value是子组件的一个数据成员
      else
        console.log("确定了" + this.bsModalRef.content.value);
    });

子组件ts代码:

import { Component, OnInit } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})

export class DetailComponent implements OnInit {
  constructor(public bsModalRef: BsModalRef) {
    console.log(this.bsModalRef.content);
  }
  public value: string = "default";
  ngOnInit() {
  }
  title: string;//调用者给title进行了赋值
  isCancel: boolean = true;
  btnCloseClick() {
    //this.bsModalRef.content = "===";
    this.bsModalRef.hide();
  }

  btnConfirmClick() {
    this.isCancel = false;
    this.bsModalRef.hide();
  }
}

子组件html:

<div>
  <label>输入内容:</label> <input id="tbValue" type="text" [(ngModel)]="value" />
</div>
<div>
  <button name="Close" class="btn btn-primary" (click)="btnCloseClick()">close</button>
  <button name="Confirm" class="btn btn-primary" (click)="btnConfirmClick()">close</button>
</div>

这里在子组件中加入了一个文本输入框,并和value成员进行绑定。弹出子组件后,输入内容,返回给调用者。

有了这种机制可以方便的实现二级窗体功能。

猜你喜欢

转载自blog.csdn.net/henreash/article/details/81434417