未处理的承诺拒绝:由以下原因引起:无法读取 null 的 属性 'touched'
Unhandled Promise rejection: caused by: Cannot read property 'touched' of null
我试图在下面的表单中执行表单验证,但验证没有发生。我遇到错误
"Unhandled Promise rejection: Error in
app/customers/customer.component.html:34:20 caused by: Cannot read
property 'touched' of null ;".
我正在使用 FormBuilder 和内置验证器。
这是我的组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Customer } from './customer';
@Component({
selector: 'my-signup',
templateUrl: './app/customers/customer.component.html'
})
export class CustomerComponent implements OnInit {
customerForm: FormGroup;
customer: Customer= new Customer();
constructor(private fb: FormBuilder){}
ngOnInit(): void {
this.customerForm = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(3)]],
//lastName: {value:'', disabled:true},
lastname: ['', [Validators.required, Validators.minLength(50)]],
email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
phone: '',
notification: 'email',
sendCatalog: true
});
}
populateTestData(): void {
this.customerForm.patchValue({
firstName: 'Jack',
lastName: 'Harkness',
//email: 'jack@torchwood.com',
sendCatalog: false
});
}
save() {
console.log(this.customerForm);
console.log('Saved: ' + JSON.stringify(this.customerForm.value));
}
setNotification(notifyVia: string): void{
const phoneControl = this.customerForm.get('phone');
if (notifyVia === 'text'){
phoneControl.setValidators(Validators.required);
} else {
phoneControl.clearValidators();
}
phoneControl.updateValueAndValidity();
}
}
这是我的表格。
<div class="panel panel-primary">
<div class="panel-heading">
Sign Up!
</div>
<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="save()"
[formGroup]="customerForm">
<fieldset>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('firstName').touched || customerForm.get('firstName').dirty) && !customerForm.get('firstName').valid }">
<label class="col-md-2 control-label"
for="firstNameId">First Name</label>
<div class="col-md-8">
<input class="form-control"
id="firstNameId"
type="text"
placeholder="First Name (required)"
formControlName="firstName" />
<span class="help-block" *ngIf="(customerForm.get('firstName').touched || customerForm.get('firstName').dirty) && customerForm.get('firstName').errors">
<span *ngIf="customerForm.get('firstName').errors.required">
Please enter your first name.
</span>
<span *ngIf="customerForm.get('firstName').errors.minlength">
The first name must be longer than 3 characters.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('lastName').touched || customerForm.get('lastName').dirty) && !customerForm.get('lastName').valid }">
<label class="col-md-2 control-label"
for="lastNameId">Last Name</label>
<div class="col-md-8">
<input class="form-control"
id="lastNameId"
type="text"
placeholder="Last Name (required)"
formControlName="lastName"/>
<span class="help-block" *ngIf="(customerForm.get('lastName').touched || customerForm.get('lastName').dirty) && customerForm.get('lastName').errors">
<span *ngIf="customerForm.get('lastName').errors.required">
Please enter your last name.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('email').touched || customerForm.get('email').dirty) && !customerForm.get('email').valid }">
<label class="col-md-2 control-label"
for="emailId">Email</label>
<div class="col-md-8">
<input class="form-control"
id="emailId"
type="email"
placeholder="Email (required)"
formControlName="email"/>
<span class="help-block" *ngIf="(customerForm.get('email').touched || customerForm.get('email').dirty) && customerForm.get('email').errors">
<span *ngIf="customerForm.get('email').errors.required">
Please enter your email address.
</span>
<span *ngIf="customerForm.get('email').errors.pattern">
Please enter a valid email address.
</span>
<!-- This one does not work -->
<span *ngIf="customerForm.get('email').errors.email">
Please enter a valid email address.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': !customerForm.get('phone').valid }">
<label class="col-md-2 control-label"
for="phoneId">Phone</label>
<div class="col-md-8">
<input class="form-control"
id="phoneId"
type="tel"
placeholder="Phone"
formControlName = "phone" />
<span class="help-block" *ngIf="customerForm.get('phone').errors">
<span *ngIf="customerForm.get('phone').errors.required">
Please enter your phone number.
</span>
</span>
</div>
</div>
<div class="form-group" >
<label class="col-md-2 control-label">Send Notifications</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio"
value="email"
formControlName = "notification">Email
</label>
<label class="radio-inline">
<input type="radio"
value="text"
formControlName = "notification">Text
</label>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-8 checkbox" >
<label>
<input id="sendCatalogId"
type="checkbox"
formControlName="sendCatalog" >
Send me your catalog
</label>
</div>
</div>
<!-- <div *ngIf="customer.sendCatalog">
<div class="form-group" >
<label class="col-md-2 control-label">Address Type</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="home"
[(ngModel)]="customer.addressType"
name="addressType">Home
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="work"
[(ngModel)]="customer.addressType"
name="addressType">Work
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="other"
[(ngModel)]="customer.addressType"
name="addressType">Other
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="street1Id">Street Address 1</label>
<div class="col-md-8">
<input type="text"
class="form-control"
id="street1Id"
placeholder="Street address"
[(ngModel)]="customer.street1"
name="street1">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="street2Id">Street Address 2</label>
<div class="col-md-8">
<input type="text"
class="form-control"
id="street2Id"
placeholder="Street address (second line)"
[(ngModel)]="customer.street2"
name="street2">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="cityId">City, State, Zip Code</label>
<div class="col-md-3">
<input type="text"
class="form-control"
id="cityId"
placeholder="City"
[(ngModel)]="customer.city"
name="city">
</div>
<div class="col-md-3">
<select class="form-control"
id="stateId"
[(ngModel)]="customer.state"
name="state">
<option value="" disabled selected hidden>Select a State...</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</div>
<div class="col-md-2">
<input type="number"
class="form-control"
id="zipId"
placeholder="Zip Code"
[(ngModel)]="customer.zip"
name="zip">
</div>
</div>
</div>-->
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<span>
<button class="btn btn-primary"
type="submit"
[disabled]="!customerForm.valid">
Save
</button>
</span>
<span>
<button class="btn btn-primary"
type="button"
(click)="populateTestData()">
Test Data
</button>
</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<br>Dirty: {{ customerForm.dirty }}
<br>Touched: {{ customerForm.touched }}
<br>Valid: {{ customerForm.valid }}
<br>Value: {{ customerForm.value | json }}
任何人都可以帮助确定此错误的原因吗?
您可以尝试使用保存导航运算符来防止错误:
customerForm.get('firstName')?.touched
或者,作为一种不同的方法,您可以尝试在您的组件中使用 getter 来获取 formGroup
属性,而不是直接从您的 HTML 中调用方法,例如,在您的 CustomerComponent
使用:
get firstName() { return this.customerForm.get('firstName') };
get lastName() { return this.customerForm.get('lastName') };
// ... etc
现在在您的 HTML 而不是使用:
customerForm.get('firstName').touched
您可以使用
firstName.touched
PS:确保你的 ts 和 html 中的大小写匹配,即 - lastName
!== lastname
我试图在下面的表单中执行表单验证,但验证没有发生。我遇到错误
"Unhandled Promise rejection: Error in app/customers/customer.component.html:34:20 caused by: Cannot read property 'touched' of null ;".
我正在使用 FormBuilder 和内置验证器。 这是我的组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Customer } from './customer';
@Component({
selector: 'my-signup',
templateUrl: './app/customers/customer.component.html'
})
export class CustomerComponent implements OnInit {
customerForm: FormGroup;
customer: Customer= new Customer();
constructor(private fb: FormBuilder){}
ngOnInit(): void {
this.customerForm = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(3)]],
//lastName: {value:'', disabled:true},
lastname: ['', [Validators.required, Validators.minLength(50)]],
email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+')]],
phone: '',
notification: 'email',
sendCatalog: true
});
}
populateTestData(): void {
this.customerForm.patchValue({
firstName: 'Jack',
lastName: 'Harkness',
//email: 'jack@torchwood.com',
sendCatalog: false
});
}
save() {
console.log(this.customerForm);
console.log('Saved: ' + JSON.stringify(this.customerForm.value));
}
setNotification(notifyVia: string): void{
const phoneControl = this.customerForm.get('phone');
if (notifyVia === 'text'){
phoneControl.setValidators(Validators.required);
} else {
phoneControl.clearValidators();
}
phoneControl.updateValueAndValidity();
}
}
这是我的表格。
<div class="panel panel-primary">
<div class="panel-heading">
Sign Up!
</div>
<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="save()"
[formGroup]="customerForm">
<fieldset>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('firstName').touched || customerForm.get('firstName').dirty) && !customerForm.get('firstName').valid }">
<label class="col-md-2 control-label"
for="firstNameId">First Name</label>
<div class="col-md-8">
<input class="form-control"
id="firstNameId"
type="text"
placeholder="First Name (required)"
formControlName="firstName" />
<span class="help-block" *ngIf="(customerForm.get('firstName').touched || customerForm.get('firstName').dirty) && customerForm.get('firstName').errors">
<span *ngIf="customerForm.get('firstName').errors.required">
Please enter your first name.
</span>
<span *ngIf="customerForm.get('firstName').errors.minlength">
The first name must be longer than 3 characters.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('lastName').touched || customerForm.get('lastName').dirty) && !customerForm.get('lastName').valid }">
<label class="col-md-2 control-label"
for="lastNameId">Last Name</label>
<div class="col-md-8">
<input class="form-control"
id="lastNameId"
type="text"
placeholder="Last Name (required)"
formControlName="lastName"/>
<span class="help-block" *ngIf="(customerForm.get('lastName').touched || customerForm.get('lastName').dirty) && customerForm.get('lastName').errors">
<span *ngIf="customerForm.get('lastName').errors.required">
Please enter your last name.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': (customerForm.get('email').touched || customerForm.get('email').dirty) && !customerForm.get('email').valid }">
<label class="col-md-2 control-label"
for="emailId">Email</label>
<div class="col-md-8">
<input class="form-control"
id="emailId"
type="email"
placeholder="Email (required)"
formControlName="email"/>
<span class="help-block" *ngIf="(customerForm.get('email').touched || customerForm.get('email').dirty) && customerForm.get('email').errors">
<span *ngIf="customerForm.get('email').errors.required">
Please enter your email address.
</span>
<span *ngIf="customerForm.get('email').errors.pattern">
Please enter a valid email address.
</span>
<!-- This one does not work -->
<span *ngIf="customerForm.get('email').errors.email">
Please enter a valid email address.
</span>
</span>
</div>
</div>
<div class="form-group"
[ngClass]="{'has-error': !customerForm.get('phone').valid }">
<label class="col-md-2 control-label"
for="phoneId">Phone</label>
<div class="col-md-8">
<input class="form-control"
id="phoneId"
type="tel"
placeholder="Phone"
formControlName = "phone" />
<span class="help-block" *ngIf="customerForm.get('phone').errors">
<span *ngIf="customerForm.get('phone').errors.required">
Please enter your phone number.
</span>
</span>
</div>
</div>
<div class="form-group" >
<label class="col-md-2 control-label">Send Notifications</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio"
value="email"
formControlName = "notification">Email
</label>
<label class="radio-inline">
<input type="radio"
value="text"
formControlName = "notification">Text
</label>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-8 checkbox" >
<label>
<input id="sendCatalogId"
type="checkbox"
formControlName="sendCatalog" >
Send me your catalog
</label>
</div>
</div>
<!-- <div *ngIf="customer.sendCatalog">
<div class="form-group" >
<label class="col-md-2 control-label">Address Type</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="home"
[(ngModel)]="customer.addressType"
name="addressType">Home
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="work"
[(ngModel)]="customer.addressType"
name="addressType">Work
</label>
<label class="radio-inline">
<input type="radio" id="addressType1Id" value="other"
[(ngModel)]="customer.addressType"
name="addressType">Other
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="street1Id">Street Address 1</label>
<div class="col-md-8">
<input type="text"
class="form-control"
id="street1Id"
placeholder="Street address"
[(ngModel)]="customer.street1"
name="street1">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="street2Id">Street Address 2</label>
<div class="col-md-8">
<input type="text"
class="form-control"
id="street2Id"
placeholder="Street address (second line)"
[(ngModel)]="customer.street2"
name="street2">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label"
for="cityId">City, State, Zip Code</label>
<div class="col-md-3">
<input type="text"
class="form-control"
id="cityId"
placeholder="City"
[(ngModel)]="customer.city"
name="city">
</div>
<div class="col-md-3">
<select class="form-control"
id="stateId"
[(ngModel)]="customer.state"
name="state">
<option value="" disabled selected hidden>Select a State...</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
</div>
<div class="col-md-2">
<input type="number"
class="form-control"
id="zipId"
placeholder="Zip Code"
[(ngModel)]="customer.zip"
name="zip">
</div>
</div>
</div>-->
<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<span>
<button class="btn btn-primary"
type="submit"
[disabled]="!customerForm.valid">
Save
</button>
</span>
<span>
<button class="btn btn-primary"
type="button"
(click)="populateTestData()">
Test Data
</button>
</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<br>Dirty: {{ customerForm.dirty }}
<br>Touched: {{ customerForm.touched }}
<br>Valid: {{ customerForm.valid }}
<br>Value: {{ customerForm.value | json }}
任何人都可以帮助确定此错误的原因吗?
您可以尝试使用保存导航运算符来防止错误:
customerForm.get('firstName')?.touched
或者,作为一种不同的方法,您可以尝试在您的组件中使用 getter 来获取 formGroup
属性,而不是直接从您的 HTML 中调用方法,例如,在您的 CustomerComponent
使用:
get firstName() { return this.customerForm.get('firstName') };
get lastName() { return this.customerForm.get('lastName') };
// ... etc
现在在您的 HTML 而不是使用:
customerForm.get('firstName').touched
您可以使用
firstName.touched
PS:确保你的 ts 和 html 中的大小写匹配,即 -
lastName
!== lastname