2016-08-30 113 views
2

基本上我想在頁面加載完成後立即使用Angular 2打字稿打開一個引導模式。在頁面加載Angular 2打字稿時打開ng2bootstrap模式

截至目前,模態獲得的點擊按鈕打開。我試着用下面的這個.mModal.show(),但是它給出了一個錯誤,如下所示 -

例外:錯誤:未捕獲(承諾):TypeError:無法讀取未定義的屬性'背景'

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">&times;</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> 

回答

2

嘗試將OnInit的代碼移到ngAfterViewChecked

+0

不確定ngAfterViewChecked,因爲這個事件發生在每個DoCheck事件上。我認爲最好使用ngAfterContentInit或ngAfterViewInit。 – cleric

1

onInitlifecycle hook檢查當前組件是否已經初始化,而不是孩子。你需要的是ngAfterContentInit,這將等待孩子們初始化。