I am working on an angular2 project and I have 2 components namely: home and first.
My home.component.html is as below :-
Why using jquery?
$("#login-modal").modal('show');
Give Angular Material dialog a try!
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 $;
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.