我正在运行代码中测试 ngOnChanges 方法。但似乎 ngOnchanges 没有被调用,尽管它可以编译。下面是我的代码。
创建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>
创建-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.model.ts:
export class Employee {
id: number;
fullName: string;
}
ngOnChanges 方法根本没有被解雇。有什么输入吗?