我正在尝试在 Angular 6 中进行表单验证
html代码
<form [formGroup]="providerForm" (ngSubmit)="onClickSubmit()">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" required [(ngModel)]="provider.name"
name="name" placeholder="Name" formControlName="name">
<div *ngIf="submitted && f.name.errors" class="invalid-feedback">
<div *ngIf="f.name.errors.required"> Name is required</div>
</div>
</div>
</form>
组件.ts
export class ProviderserviceComponent implements OnInit {
constructor(private modalService: NgbModal, public cdRef: ChangeDetectorRef, private formBuilder: FormBuilder) { }
submitted = false;
provider: Provider = new Provider();
providerForm: FormGroup;
ngOnInit() {
this.providerForm = this.formBuilder.group({
name: ['', Validators.required]
});
}
get f() { return this.providerForm.controls; }
onClickSubmit(data) {
this.submitted = true;
}
在 app.modeule.ts,component.ts 文件中,我添加了以下模块 FormBuilder、FormGroup、Validators,当我在 html 文件上调试时显示错误。