如何在Angular的ngOnInit生命周期中自动打开ng-bootstrap modal弹窗
实现方案
1. 调整TypeScript代码
修改组件逻辑,先获取弹窗模板引用,再在初始化生命周期中触发弹窗:
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-modal-demo', templateUrl: './modal-demo.component.html' }) export class ModalDemoComponent implements OnInit { // 获取HTML中#content对应的模板引用,static设为true保证ngOnInit阶段可访问 @ViewChild('content', { static: true }) contentTemplate!: TemplateRef<any>; constructor(private modalService: NgbModal) {} ngOnInit(): void { // 组件初始化时直接调用弹窗方法 this.openSm(this.contentTemplate); } openSm(content: TemplateRef<any>) { this.modalService.open(content, { size: 'sm' }); } }
2. 调整HTML代码
直接删除不需要的触发按钮,仅保留弹窗模板即可:
<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">×</span> </button> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" (click)="modal.close('Close click')">Close</button> </div> </ng-template>
注意事项
Angular 8及以上版本@ViewChild的static参数默认为false,必须手动设置为true才能在ngOnInit阶段正常获取到模板引用。
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

