首页 > 解决方案 > ng-bootstrap 模式在 ngOnInit() 上打开

问题描述

我想从我的打字稿代码中打开模态,即当组件加载到 ngOnit() 时,模态弹出窗口应该打开,我不想在 html 文件上创建按钮。

HTML:

<button class="btn btn-outline-primary mb-2 mr-2" (click)="openSm(content)">Small modal</button>

<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p>One fine body&hellip;</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button>
  </div>
</ng-template>

TS:

openSm(content) {
    this.modalService.open(content, { size: 'sm' });
  }

堆栈闪电链接

我想在 ngOnit() 函数上打开模式。

标签: javascriptangulartypescriptbootstrap-modalng-bootstrap

解决方案


只需使用 ViewChild 获取“内容”并在 ngOnInit 调用 this.open(this.content)

  @ViewChild("content",{static:true}) content:ElementRef;

  constructor(private modalService: NgbModal) {}

  ngOnInit()
  {
    this.openSm(this.content)
  }

你的分叉堆栈闪电战

注意:我使用{static:true}并将代码放在 ngOnInit 中,因为我认为您的“内容”始终是“可见的”,否则您需要使用 ngAfterViewInit


推荐阅读