Angular2打开ngx-modal而无需单击按钮

时间:2017-03-16 14:55:30

标签: angular modal-dialog bootstrap-modal

我将在序言中说我对Angular2很新。我需要找到一种方法来打开一个登录失败的警报Modal,代码在下面评论“//登录失败”,我找到的所有例子都依赖于按钮点击,有没有办法根据布尔状态执行此操作值?

import { Component } from '@angular/core';
import { UsersService } from '../users.service';
import { Router } from '@angular/router';
import { ModalModule } from 'ngx-modal';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  constructor(private usersService: UsersService, private router: Router) {}

  user: string;
  pass: string;
  liwr: boolean = false;


  loginPressed(username, password){
  console.log(username + " " + password);


		  this.usersService.loginAttempt(username, password).subscribe(response => {
			console.log(response[1]);

      //admin login
			if (response[0].status === 'success' && response[1].userInfo.privilegeStatus === 'admin'){

				this.router.navigateByUrl('/posts');
        this.usersService.authStatus = response[1].isAuth;
        this.usersService.userSessionObj = response[1];

      //staff login
      } else if (response[0].status === 'success' && response[1].userInfo.privilegeStatus === 'staff'){

        this.router.navigateByUrl('/staff');
        this.usersService.authStatus = response[1].isAuth;
        this.usersService.userSessionObj = response[1];

      //failed login
      } else if (response[0].status === 'invalid'){

        this.liwr = true;
        console.log(this.liwr);

      }

		});
  }
<div class="row">
    <button (click)="myModal.open()">open my modal</button>
    <modal #myModal>
        <modal-header>
            <h1>Modal header</h1>
        </modal-header>
        <modal-content>
            Hello Modal!
        </modal-content>
        <modal-footer>
            <button class="btn btn-primary" (click)="myModal.close()">close</button>
        </modal-footer>
    </modal>
</div>

1 个答案:

答案 0 :(得分:5)

您可以使用ViewChild

import {ViewChild}  from '@angular/core';

export class LoginComponent {
  @ViewChild('myModal') modal: any;
  constructor() { }

  /...
  else if (response[0].status === 'invalid'){
        this.modal.open();
        this.liwr = true;
        console.log(this.liwr);

  }

 /...

}