typescript Angular 4 Reactive Forms FormControl 错误为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45950054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:51:08  来源:igfitidea点击:

Angular 4 Reactive Forms FormControl errors is null

javascriptangulartypescriptangular-reactive-forms

提问by 333Matt

If I tab through the text inputs without entering anything, the error msg divs display indicating that the required validator has fired correctly. However, if I type anything into one of the fields, the console immediately throws this error:

如果我在没有输入任何内容的情况下浏览文本输入,则会显示错误 msg divs,表明所需的验证器已正确触发。但是,如果我在其中一个字段中输入任何内容,控制台会立即抛出此错误:

Cannot read property 'required' of null

Here is my component:

这是我的组件:

import { PasswordValidators } from './../validators/password.validators';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-changepassword-form',
  templateUrl: './changepassword-form.component.html',
  styleUrls: ['./changepassword-form.component.css']
})
export class ChangepasswordFormComponent {

  form;

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      newPassword: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    })
  }

  get newPassword() {
    return this.form.get('newPassword');
  }

  get confirmPassword() {
    return this.form.get('confirmPassword');
  }

}

and HTML:

和 HTML:

<form [formGroup]="form">  
  <div class="form-group">
    <label for="newPassword">New Password</label>
    <input formControlName="newPassword" id="newPassword" type="text" class="form-control">
    <div class="alert alert-danger" *ngIf="newPassword.touched && newPassword.errors.required">
      Required
    </div>
  </div>
  <div class="form-group">
    <label for="confirmPassword">Confirm Password</label>
    <input formControlName="confirmPassword" id="confirmPassword" type="text" class="form-control">
    <div class="alert alert-danger" *ngIf="confirmPassword.touched && confirmPassword.errors.required">
      Required
    </div>
  </div>

  <p><button class="btn btn-primary">Submit</button></p>

</form>

回答by Vega

You can also use the following syntax and it will work without the need to have a value first:

您还可以使用以下语法,它无需先有值即可工作:

form.get('newPassword').hasError('required')

This will check for 'required' in the errors.

这将检查错误中的“必需”。

This will work as well and it's more concise :

这也能工作,而且更简洁:

form.hasError('required','newPassword')

If you are compiling with AOT option, according to this article, you should privilege hasError() syntax:

如果你使用 AOT 选项编译,根据这篇文章,你应该特权 hasError() 语法:

Don't use control.errors?.someError, use control.hasError(‘someError')

不要使用 control.errors?.someError,使用 control.hasError('someError')

回答by DeborahK

That error is coming from this:

该错误来自于此:

*ngIf="newPassword.touched && newPassword.errors.required"

When you put in a value, there is no longer an errors collection so checking newPassword.errors.requiredgenerates that Cannot read property 'required' of nullerror.

当您输入一个值时,不再有错误集合,因此检查会newPassword.errors.required生成该Cannot read property 'required' of null错误。

Try something like this instead:

试试这样的:

*ngIf="newPassword.touched && newPassword.errors?.required"

As an example, mine looks like this:

例如,我的看起来像这样:

            <div class="col-md-8">
                <input class="form-control" 
                        id="productNameId" 
                        type="text" 
                        placeholder="Name (required)"
                        required
                        minlength="3"
                        [(ngModel)] = product.productName
                        name="productName"
                        #productNameVar="ngModel" />
                <span class="help-block" *ngIf="(productNameVar.touched ||
                                                 productNameVar.dirty || product.id !== 0) &&
                                                 productNameVar.errors">
                    <span *ngIf="productNameVar.errors.required">
                        Product name is required.
                    </span>
                    <span *ngIf="productNameVar.errors.minlength">
                        Product name must be at least three characters.
                    </span>
                </span>
            </div>