未定义标识符“已提交”

时间:2019-05-06 04:35:00

标签: angular

我正在尝试使用ReactiveForms在angular中实现客户端验证。我在

行中看到“未定义标识符'submitted'的错误。'FormGroup'不包含这样的成员”
<div *ngIf="form.submitted && !firstName.valid">

,当我实际提交时,我的验证标签没有显示。但是,如果我删除“ form.submitted”,则会显示我的验证标签。请在下面查看我的代码:

这在 component.ts 中开始创建表单:

ngOnInit() {
    this.createForm();
}
createForm() {
    this.form = new FormGroup({
      firstName: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required]
      }),
      middleName: new FormControl(null, {
        updateOn: 'submit',
      }),
      lastName: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required]
      }),
      userName: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required]
      }),
      email: new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.pattern(this.emailRegex)]
      }),
      password:  new FormControl(null, {
        updateOn: 'submit',
        validators: [Validators.required]
      })
    });
}

,在我的 html 中,我像这样使用它:

<form [formGroup]="form" (ngSubmit)="form.valid && onSubmit(form)">
  <input type="text"
    matInput
    formControlName="firstName"
    placeholder="First Name"
    required
    [ngClass]="{ 'invalid-textbox' : form.submitted && !firstName.valid }"
  />
  <div *ngIf="form.submitted && !firstName.valid">
    <label class="validation-message">First Name is required</label>
  </div>
  ... Many others ...
  <input type="submit" value="Sign Up" />
 </form>

请帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

将代码更改为

使用formBuilder生成表单的TS文件

constructor(private formBuilder: FormBuilder) {
}

    form: FormGroup;

         createForm() {
            this.form = this.formBuilder.group({
              firstName: ['', Validators.required],
              middleName: [''],
              lastName: ['', Validators.required],
              email: ['', [Validators.required, Validators.email]],
              password: ['', [Validators.required, Validators.minLength(6)]],

            });
          }

          ngOnInit() {
            this.createForm();
          }

HTML

<div class="form-group">
                        <label>First Name</label>
                        <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
                        <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
                            <div *ngIf="f.firstName.errors.required">First Name is required</div>
                        </div>
                    </div>

https://stackblitz.com/edit/angular-7-validate-form-angular

答案 1 :(得分:1)

然后在 component.ts 文件中创建归档的submitted=false

createForm() {
this.submitted = true;

if (this.registrationFrom.invalid) {
  return;
}
alert('SUCCESS!! :-));'