4

基本上,我想在页面加载完成后立即使用 Angular 2 打字稿打开一个引导模式。

截至目前,模态获取在单击按钮时打开。我尝试使用 this.smModal.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>
4

2 回答 2

2

尝试将 onInit 代码移动到 ngAfterViewChecked

于 2016-08-30T20:55:46.837 回答
1

onInit 生命周期钩子检查当前组件是否已初始化,而不是子组件。你需要的是ngAfterContentInit,它将等待孩子被初始化。

于 2016-08-30T20:58:46.823 回答