2017-03-16 36 views
1

我會先說我對Angular2很新。我需要找到一種方法來打開一個登錄失敗的警告Modal,代碼在「//失敗登錄」下面註釋,我發現所有的例子都依賴於一個按鈕的點擊,有沒有一種方法可以根據布爾狀態值?Angular2沒有按鈕就打開ngx-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); 
 

 

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

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

 
\t \t \t \t 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); 
 

 
     } 
 

 
\t \t }); 
 
    }
<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>

回答

4

您可以使用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); 

    } 

/... 

} 
+0

謝謝主席先生!很棒。 –