Angular 8页面加载时自动打开BsModal的实现方法
解决Angular 8页面加载时自动打开BsModal的问题
嘿,我来帮你搞定这个问题!你遇到的核心问题是在ngOnInit里调用模态框时,模板引用还没初始化完成——因为ngOnInit是组件初始化的早期阶段,这时候组件的视图还没完全渲染,@ViewChild获取到的privacyPopup还是undefined,自然没法触发模态框。
下面给你两种靠谱的解决方案:
方案1:使用ngAfterViewInit生命周期钩子
这个钩子会在组件的视图(包括子视图)完全初始化完成后触发,这时候@ViewChild就能正确拿到模板引用了。修改你的TS代码如下:
import { Component, OnInit, ViewChild, TemplateRef, AfterViewInit } from '@angular/core'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; @Component({ selector: 'app-filemanager', templateUrl: './filemanager.component.html' }) export class FilemanagerComponent implements OnInit, AfterViewInit { @ViewChild('showPrivacyPop') public privacyPopup: TemplateRef<any>; modalRef: BsModalRef; config = { animated: true }; constructor(private modalService: BsModalService) { } ngOnInit() { // 这里视图还没准备好,不要在这里调用模态框 } ngAfterViewInit() { // 视图初始化完成,现在可以安全打开模态框了 this.openModal(this.privacyPopup); } openModal(template: TemplateRef<any>) { console.log(template); this.modalRef = this.modalService.show(template, this.config); } }
方案2:给@ViewChild添加{ static: true }选项(Angular 8+支持)
如果你的模板元素不是通过*ngIf这类结构指令动态渲染的,可以给@ViewChild加上{ static: true }配置,这样Angular会在组件初始化阶段就解析模板引用,你就能在ngOnInit里直接调用了:
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; @Component({ selector: 'app-filemanager', templateUrl: './filemanager.component.html' }) export class FilemanagerComponent implements OnInit { // 添加{ static: true },让Angular提前解析模板引用 @ViewChild('showPrivacyPop', { static: true }) public privacyPopup: TemplateRef<any>; modalRef: BsModalRef; config = { animated: true }; constructor(private modalService: BsModalService) { } ngOnInit() { // 现在这里能拿到有效的模板引用了 this.openModal(this.privacyPopup); } openModal(template: TemplateRef<any>) { console.log(template); this.modalRef = this.modalService.show(template, this.config); } }
两种方案都能解决你的问题,根据你的实际场景选择就行:如果模板是动态渲染的(比如用了*ngIf),优先选方案1;如果模板是固定存在的,方案2更简洁。
内容的提问来源于stack exchange,提问作者Sakkeer A
相关产品推荐
相关产品推荐

