角度4 ngOnChanges未显示更改

时间:2017-08-25 10:23:33

标签: angular typescript events

我尝试在角度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");
        }
    }

我只是检查电子邮件输入是否有变化,例如,如果有人输入或类似内容,但我没有看到更改,我看不到它在控制台中打印任何内容。

1 个答案:

答案 0 :(得分:3)

如果您使用的是子组件,则可以在输入中使用 grayed-out ,在您的情况下,只需使用 ngOnChanges

(change)="onChange($event)"