Ошибка при валидации форм Angular2
Помогите разобраться с валидацией форм в Angular2. Не могу найти ошибку в коде. valueChanges.subscribe выдает undefined. А результат onAdd в консоли: {id: null, name: null}. Код валидации на Angular2:
export class AdminInputComponent implements OnInit{
product: Row = new Row();
productForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.buildForm();
}
buildForm() {
this.productForm = this.fb.group({
"id": [this.product.id, [
Validators.required
]],
"name": [this.product.name, [
Validators.required
]]
});
this.productForm.valueChanges
.subscribe(data => this.onValueChange(data));
this.onValueChange();
}
onValueChange(data?: any) {
console.log(data)
if (!this.productForm) return;
let form = this.productForm;
for (let field in this.formErrors) {
this.formErrors[field] = "";
let control = form.get(field);
if (control && control.dirty && !control.valid) {
let message = this.validationMessages[field];
for (let key in control.errors) {
this.formErrors[field] += message[key] + " ";
}
}
}
}
onAdd() {
console.log(this.productForm.value);
}
HTML форма:
<form formGroup="productForm">
<div class="form-group">
<label for="id">Id:</label>
<input type="text" id="id" class="form-control" formControlName="id"><br>
<div *ngIf="formErrors.id" class="alert_invalid">
{{ formErrors.id }}
</div>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" class="form-control" formControlName="name"><br>
<div *ngIf="formErrors.name" class="alert_invalid">
{{ formErrors.name }}
</div>
</div>
<button type="button" class="btn" (click)="onAdd()">Add</button>