且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 4 Reactive Forms FormControl错误为空

更新时间:2023-12-02 23:31:46

该错误来自于此:

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

当您输入值时,不再有错误集合,因此检查 newPassword.errors.required 会生成无法读取null的'required'错误属性.

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

尝试这样的方法:

*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>