import { Component, OnInit,Input } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
styleUrls: ['app.component.css'],
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
@Input() awesomeForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.awesomeForm = this.fb.group({
awesome: ['', Validators.required]
})
this.awesomeForm.valueChanges.subscribe(changes => {
// do what you need with the form fields here
// you can access a form field via changes.fieldName
this.validateForm(changes);
});
}
public resetForm() {
this.awesomeForm.reset();
console.log('Error state is still active. :(');
}
public validateForm(changes: any) {
console.log('How to trigger validation without hacking focus events on the dom element?');
console.log('triggered and got changes',changes)
}
}
您可以订阅FormGroup
object valueChanges
observable 并且它具有表单上存在的所有字段,一旦您获得字段值,您基本上可以在每个字段更改方法上触发您的验证功能并将其传递给validateForm(changes:any)