你应该使用FormGroup。
使用[formGroup]="myForm"。只有满足每个字段的验证器才能提交请求。后者通过formControlName 链接。在所有验证器都满意之前,该按钮将被禁用。
registration.component.html:
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
<p class="form-group">
<label for="username">Name</label>
<input
id="name"
type="text"
name="name"
formControlName="name"
value=""
class="form-control"
/>
<span class="invalid-feedback">
Please provide a valid name.
</span>
</p>
<p class="form-group">
<label for="phone">Telephone</label>
<input
id="telephone"
type="text"
name="telephone"
formControlName="telephone"
value=""
class="form-control"
/>
<span class="invalid-feedback">
Please provide a valid telephone number.
</span>
</p>
<p>
<button
type="submit"
class="btn btn-primary btn-block"
[disabled]="!registrationForm.valid"
translate
>Sign In</button>
</p>
</form>
registration.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
export interface Model {
name?: string;
telephone?: string;
}
@Component({
selector: 'app-registration-form',
templateUrl: './registration.component.html'
})
export class RegistrationComponent implements OnInit {
registrationForm: FormGroup;
ngOnInit() {
if (
this.registrationForm === undefined ||
this.registrationForm === null
) {
this.registrationForm = new FormGroup( {
name: new FormControl('', Validators.required, Validators.minLength(1)),
telephone:new FormControl('', Validators.required, Validators.minLength(1))
});
}
}
onSubmit() {
if ( this.registrationForm.valid ) {
const formValue = this.registrationForm.value;
const model: Model = {
name: formValue.name,
telephone: formValue.telephone
};
console.log('model', model);
}
}
}
您可以阅读更多here。您可以使用任何类型的验证器,也可以构建自己的验证器。例如,您可以对您的电话号码应用一个正则表达式,以使用 Validators.Pattern('yourRegxTelephonePattern') 了解输入是否有效。