ngOnChanges没有被解雇

时间:2019-01-29 09:38:59

标签: angular ngonchanges

我正在运行代码中测试ngOnChanges方法。但是,尽管ngOnchanges可以编译,但似乎没有被调用。下面是我的代码。

create-employee.component.html:

<form #employeeForm="ngForm"  (ngSubmit)=saveEmployee(employeeForm)>
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h3 class="panel-title"> Create Employee</h3>
    </div>
    <div class="panel-body">
      <div class="form-group" [class.has-error]="fullName.invalid && fullName.touched" [class.has-success]="fullName.valid">
        <label for="fullName"class="control-label">Full Name</label>
        <input required type ="text"  class= "form-control" 
          name="fullName1" 
          [(ngModel)]="employee.fullName"
          #fullName="ngModel" id="fullName">
        <span class="help-block" *ngIf="fullName.invalid && fullName.touched">
          Full Name is Required
        </span>
      </div>
    </div>
    <div class="panel-footer">
     <button  [disabled]="employeeForm.invalid" type ="submit" class= "btn btn-primary" > Save </button>
    </div>
  </div>
  {{employeeForm.value|json}}
  employee: {{employee| json}}
  employee.isActive: {{employee.isActive}}
</form>

create-employee.component.ts:

import { Component,OnChanges, OnInit ,SimpleChanges,Input} from '@angular/core';
import { NgForm } from '@angular/Forms';
import { Department } from '../models/department.model';
import { BsDatepickerModule,BsDatepickerConfig} from 'ngx-bootstrap/datepicker';
import { Employee } from '../models/employee.model';

@Component({
  selector: 'app-create-employee',
  templateUrl: './create-employee.component.html',
  styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit, OnChanges {

  constructor() {}

  saveEmployee( employeeForm:NgForm): void {
    console.log(employeeForm);
    console.log("employee = " + JSON.stringify(this.employee));  
  }


  allMsgChangeLogs: string[] = [];
  allEmployeeChangeLogs: string[] = [];

  @Input() employee:Employee = { 
    id: null,
    fullName: 'Jay',
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log("inside on changes"); 
    for (let propName in changes) {  

      let change = changes[propName];

      let curVal  = JSON.stringify(change.currentValue);
      let prevVal = JSON.stringify(change.previousValue);
      let changeLog = `${propName}: currentValue = ${curVal}, previousValue = ${prevVal}`;

      if (propName === 'employee') {
          this.allEmployeeChangeLogs.push(changeLog);
          console.log(changeLog);
      } else {
         console.log("change detecetd");
      }
    }
  }

在表单中使用的模型对象employee为:employee.model.ts:

export class Employee {
    id: number;
    fullName: string;
}

ngOnChanges方法根本不会被触发。有输入吗?

1 个答案:

答案 0 :(得分:0)

@Input用于angular components之间的父子交互。从您的代码中看不到您将employee传递到CreateEmployeeComponent的地方。因此employee始终是undefined,而ngOnChanges不会触发。 https://angular.io/guide/component-interaction在这里还有更多。