我正在尝试实现一种功能,当用户访问登录页面并在登录页面上停留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">×</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