0

我正在尝试在 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 文件上调试时显示错误。

在此处输入图像描述

4

3 回答 3

0

你不应该使用<input type="text" class="form-control" id="name" required [(ngModel)]="provider.name" ngmodel 反应形式不需要。匹配是在 上完成的formControlName。将数据传递给表单是通过setValue/完成的patchValue。请查看文档以获取最小示例。

于 2019-03-22T06:50:56.510 回答
0

请不要使用FormBuilderand ngModel,因为它们都在使用相同的工作

例如尝试删除

this.providerForm = this.formBuilder.group({
       name: ['', Validators.required]
});
于 2019-07-12T09:25:12.633 回答
0

HTML 文件

<form [formGroup]="providerForm" (ngSubmit)="onClickSubmit()">
   <div class="form-group">
    <label for="fname">Name</label>
     <input type="text" class="form-control" id="fname" required (ngModel)]="provider.fname" placeholder="Name" formControlName="fname" #fname>

     <div *ngIf="submitted && f.fname.errors" class="invalid-feedback">
      <div *ngIf="f.fname.errors.required"> Name is required</div>
      </div>
     </div>
</form>

组件.ts

export class ProviderserviceComponent implements OnInit {
        constructor(private formBuilder: FormBuilder) { }
         submitted = false;
        provider: Provider = new Provider();
        providerForm: FormGroup;

        ngOnInit() {
            this.providerForm = this.formBuilder.group({
                fname: ['', Validators.required]
            });

        }
        get f() { return this.providerForm.controls; }
        onClickSubmit(data) {
            this.submitted = true;

        }
于 2019-07-12T09:14:28.733 回答