基本上我想在页面加载完成后立即使用Angular 2打字稿打开一个bootstrap模式。
截至目前,点击按钮即可打开模态获取。我尝试使用this.smModal.show(),您将在下面找到它,但它给出了如下错误 -
EXCEPTION:错误:未捕获(在承诺中):TypeError:无法读取未定义的属性“backdrop”
home.component.ts文件是
import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
import {CORE_DIRECTIVES} from '@angular/common';
import { Router } from '@angular/router';
import {MODAL_DIRECTIVES, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'my-home'
templateUrl: 'app/home.component.html',
directives: [MODAL_DIRECTIVES, CORE_DIRECTIVES],
viewProviders:[BS_VIEW_PROVIDERS],
styleUrls: ['app/home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild('smModal') public smModal: ModalDirective;
constructor(private router: Router) { }
ngOnInit(){
console.log("Open Modal on init itself.")
this.smModal.show()
}
redirectToOtp(){
this.router.navigate(['./otp']);
}
}
Html如下
<button type="button" class="btn btn-primary" (click)="smModal.show()">Sign Docs</button>
<div bsModal #smModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<!-- <button type="button" class="close" aria-label="Close" (click)="smModal.hide()">
<span aria-hidden="true">×</span>
</button> -->
</div>
<div class="modal-body">
<div style="font-size:12px; text-align:center;border-bottom:1px solid #e5e5e5;">
<div style="color:#696969;">
<span>Gmail account? Proceed with</span>
</div>
<div style="padding-top:10px;">
<button type="button" class="btn btn-danger" style="background-color:#dd4b39;border-radius:0px;" (click)="redirectToOtp()" (click)="smModal.hide()">Google</button>
</div>
<div style="color:#696969;padding-top:10px;padding-bottom:10px;">
<span>TIP:</span><span style="color:#939393;font-size:10px;">If using multiple Gmail accounts, select the account shown above</span>
</div>
</div>
<div style="padding-top:10px;" class="hidden-xs">
<div style="text-align:center;">
</div>
<div style="color:#939393;font-size:10px; padding-left:45px;padding-right:45px">
</div>
</div>
<div class="" style="padding-top:10px;text-align:center;">
<button type="button" class="btn btn-primary" style="border-radius:0px;" (click)="redirectToOtp()" (click)="smModal.hide()">Continue</button>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:2)
尝试将onInit代码移动到ngAfterViewChecked
答案 1 :(得分:1)
onInit
lifecycle hook检查当前组件是否已初始化,而不是子项。你需要的是ngAfterContentInit
,它将等待孩子们被初始化。