Open bootstrap modal on page load angular 2

前端 未结 3 1501
醉梦人生
醉梦人生 2021-02-11 01:46

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:06

    Why using jquery?

    $("#login-modal").modal('show');
    

    Give Angular Material dialog a try!

    0 讨论(0)
  • 2021-02-11 02:11

    Add jquery cdn to the head of your index.html. Something like this:

    <script
     src="https://code.jquery.com/jquery-3.2.1.min.js"
     integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
     crossorigin="anonymous"></script>
    

    Don't forget to declare var $ at the top of your .ts file before @Component decorator .i.e.

    declare var $;
    
    0 讨论(0)
  • 2021-02-11 02:13

    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:

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

    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:

    <li><a href="#" data-toggle="modal" data-target="#login-modal" 
    (click)="myFunc()">Login</a></li>
    

    TS:

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

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

    0 讨论(0)
提交回复
热议问题