Open bootstrap modal on page load angular 2

前端 未结 3 1722
情深已故
情深已故 2021-02-11 01:37

I am working on an angular2 project and I have 2 components namely: home and first.

My home.component.html is as below :-

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-11 02:15

    To make the modal display upon user first visiting the component:

    Component's TS file:

    import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
    export class AppComponent implements OnInit{
    @ViewChild('openModal') openModal:ElementRef;
    
    title = 'app works!';
    
    ngOnInit(){
     this.openModal.nativeElement.click();
    }
    

    Component's HTML file:

    
    

    This will open the modal upon the user first visiting the page. You'll have a ghost button that the user can not see, but will be activated by using this.openModal.nativeElement.click(). Lots of possiblities using this method to open the modal.

    To open the same modal when the user clicks the login button:

    HTML:

  • Login
  • TS:

    myFunc(){
      this.openModal.nativeElement.click();
    }
    

    This may not be the most elegant solution, but it definitely works and I use it quite often.

提交回复
热议问题