1
我想在我的Angular2應用程序中使用無功的形式,但我遇到了一個異常,如下例外:未捕獲的(在承諾):類型錯誤:無法讀取屬性空
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'touched' of null TypeError: Cannot read property 'touched' of null
我的樣品的「感動」代碼是如下
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import {FormGroup, FormControl} from '@angular/forms';
import { Customer } from './customer';
@Component({
moduleId:module.id,
templateUrl: 'sign-up.reactiveForms.html'
})
export class SignupComponent {
customer: Customer= new Customer();
customerForm : FormGroup; //it assosciate html element with this root model
ngOnInit() : void {
this.customerForm=new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl(),
sendCatalog: new FormControl(true)
});
}
save() {
console.log(this.customerForm);
}
}
登錄up.reactiveForms.html文件是如下
<!-- First Name input -->
<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)"
required
minlength="3"
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>
我想弄清楚爲什麼觸摸屬性爲null。
該消息並不意味着被觸摸的屬性爲null,這意味着customerForm沒有firstName。 – jonrsharpe
嘗試了你的代碼,我無法重現你的問題,這意味着它對我來說工作得很好。作爲一個瘋狂的猜測,嘗試使用安全的導航操作符。至少應該照顧空值錯誤,但也許驗證將不起作用(?)。但嘗試...例如:'customerForm.get('firstName')?.'' – Alex