我想在 angularJS2 中使用 ReactiveFormModule 验证我的表单,假设我有这样的组件代码
export class userComponent implements OnInit {
constructor(private fb: FormBuilder) { }
userForm: FormGroup;
users = new userDetails();
ngOnInit(): void {
this.buildForm();
}
buildForm(): void {
this.userForm = this.fb.group({
'qualification': [this.users.qualification, Validators.required]
});
this.userForm.valueChanges
.subscribe(data => this.onValueChanged(data));
this.onValueChanged(); // (re)set validation messages now
}
onValueChanged(data?: any) {
debugger;
if (!this.userForm) { return; }
const form = this.userForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
onSubmit() {
this.users = this.userForm.value;
}
formErrors = {
'designation':''
};
validationMessages = {
'designation': {
'required':'Please select a designation.'
}
};
}
我有一个这样的 HTML 代码
<select class="form-control" formControlName="designation" required>
<option selected>Select Designation</option>
<optgroup label="Accounts">
<option>Trainee</option>
<option>Junior Accountant</option>
<option>Senior Accountant</option>
</optgroup>
<optgroup label="Sales">
<option>Sales Executive</option>
<option>Sales Regional Manager</option>
<option>Sales Manager</option>
</optgroup>
<optgroup label="IT">
<option>Junior Software Developer</option>
<option>Senior Software Developerr</option>
<option>Tech Lead</option>
<option>Project Lead</option>
<option>Project Manager</option>
<option>Manager</option>
</optgroup>
</select>
没有文章,实际上解释了如何验证 angularJS2 中的选择按钮,我们可以实际使用 angularJS2 验证选择元素吗?