如果我在沒有輸入任何內容的情況下通過文本輸入選項卡,錯誤消息顯示錶明所需驗證器已正確啓動。但是,如果我輸入任何東西進入的領域之一,控制檯會立即引發此錯誤:Angular 4 Reactive Forms FormControl錯誤爲空
Cannot read property 'required' of null
這裏是我的組件:
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');
}
}
和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>
謝謝,這真的把我一個循環 - 它的排序是有意義的,是有點意外。我認爲也許一個好的做法是將這些錯誤信息包與另一個與* ngIf,檢查control.isValid以避免此問題。 – 333Matt