2017-08-25 79 views
0

我尝试使用角4中的ngOnChanges,但我没有看到它的任何工作。角度4 ngOnChanges不显示更改

login.component.ts

import { AuthService } from './../../services/auth.service'; 
import { ActivatedRoute, Router } from '@angular/router'; 
import { Component, OnInit, OnChanges,SimpleChanges } from '@angular/core'; 
import { FormControl, Validators, FormBuilder, FormGroup } from '@angular/forms'; 

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    styleUrls: ['./login.component.css'] 
}) 
export class LoginComponent implements OnInit,OnChanges { 
    returnUrl: string; 
    signInForm: FormGroup; 
    errorMsg: any; 


    constructor(
     private userService: AuthService, private router: Router, private route: ActivatedRoute, private fb: FormBuilder) { 
      this.signInForm = fb.group ({ 
       'email' : new FormControl(null, Validators.compose([Validators.email, Validators.required])), 
       'password': new FormControl(null, Validators.compose([Validators.required, Validators.minLength(6)])) 
       }); 
     } 

    login() { 

     this.userService.login({email: this.signInForm.value.email, password: this.signInForm.value.password}) 
      .subscribe(
       data => { 
        this.router.navigate(['']); 

       }, 
       error => { 
        this.errorMsg = error._body; 
        console.log(this.errorMsg); 
       }); 
    } 
    ngOnChanges(changes: SimpleChanges) { 
     if(changes.email){ 
      console.log("email input change"); 
     } 
    } 

    ngOnInit() { 

    } 

} 

login.component.html

<form [formGroup]="signInForm" (ngSubmit)="login()">  
<div class="ui middle aligned center aligned grid"> 
    <div class="column"> 
    <h2 class="ui teal image header"> 
     <div class="content"> 
     Log-in to your account 
     </div> 
    </h2> 
    <div class="ui large form"> 
     <div class="ui stacked segment"> 
     <div class="field"> 
      <div class="ui left icon input"> 
      <i class="user icon"></i> 
      <input type="text" name="email" formControlName="email" placeholder="E-mail address"> 
      </div> 
      <span 

,你可以在这里看到ngOnChanges功能

ngOnChanges(changes: SimpleChanges) { 
     if(changes.email){ 
      console.log("email input change"); 
     } 
    } 

我只是检查邮件是否有输入例如,如果某人输入了类型或其他内容,但我没有看到更改,我没有看到它在控制台中显示任何内容。

回答

3

,如果您使用的是子组件,在你的情况简单地使用(change)="onChange($event)"

<input type="text" name="email" [(ngModel)]="email" (change)="onChange($event)"`** formControlName="email" placeholder="E-mail address"> 
+0

感谢您可以使用ngOnChanges输入,这正是我多么希望。 –

+0

但为什么它在我完成键入并按下tab键而不是在键入过程中工作? –

+1

然后使用(输入)=“onChange($ event) –