如何在 Angular 页面加载后触发 bootstrap 模态弹出窗口 7

How to trigger bootstrap modal popup after page loads in Angular 7

我正在尝试实现一种功能,当用户访问登录页面并在登录页面停留超过 15 秒时,模式会在大约 15 秒后加载。但是在视图加载后没有加载任何内容

HTML:

<button [hidden]="true" data-toggle="modal" data-target="#myModal"></button>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-scrollable" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="myModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

component.ts 文件

import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, AfterViewInit {
  @ViewChild('myModal') myModal:ElementRef;
  constructor() { }
  ngOnInit() { }
  ngAfterViewInit () {
    setTimeout(() =>{
      this.myModal.nativeElement.click();;
    }, 15000)
  }
}

您的代码运行完美,您只是忘记将引用变量 #myModal 添加到您的按钮。

示例:

<button #myModal [hidden]="true" data-toggle="modal" data-target="#myModal"></button>

StackBlitz 示例:

https://stackblitz.com/edit/angular-open-modal-afterviewinit-5s