1
我要驗證在angularJS2使用ReactiveFormModule我的形式,假設我有這樣的如何驗證在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.'
}
};
}
一個組件代碼,我有這樣的
<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>
一個HTML代碼沒有任何文章,這其實解釋如何驗證angularJS2中的選擇按鈕,我們是否可以使用angularJS2實際驗證select元素?