ng-bootstrap 模式在 ngOnInit() 上打开

ng-bootstrap modal open on 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' });
  }

stackblitz link

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

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

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

  constructor(private modalService: NgbModal) {}

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

你的分叉 stackblitz

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

您可以使用 viewchild 和 afterviewinit lifehook。

 @ViewChild("content") modalContent: TemplateRef<any>;


  constructor(private modalService: NgbModal) {}
ngAfterViewInit(): void {
  this.modalService.open(this.modalContent, { size: 'sm' });
}