htmlangularbootstrap-4angular7modalpopup

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


I'm trying to implement a functionality where a modal loads after about 15 seconds when the user visits the landing page and and staying on the landing page for more than 15 seconds. But nothing is getting loaded after the view loads

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 file

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)
  }
}

Solution

  • Your code is working perfect you just forgot to add reference variable #myModal to your button.

    Example :

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

    StackBlitz Example :

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